0

I have the following test application:

#include <boost/any.hpp>
#include <iostream>

void check(boost::any y)
{
    if (y.empty())
        std::cout << "empty!\n";
    else
        std::cout << "Not empty, type: " << y.type().name() << "\n";
}

int main()
{
    boost::any boostAny;
    check(boostAny);

    boost::any* boostAny2 = &boostAny;
    check(boostAny2);

    boost::any* boostAny3 = new boost::any;
    check(boostAny3);
    delete(boostAny3);
}

I compile and run like so:

g++ -std=c++11 -o test test.cpp && ./test

Output is:

empty!
Not empty, type: PN5boost3anyE
Not empty, type: PN5boost3anyE

I would expect for all 3 tests the same output. But it's not. Why? Is this a bug? Tried with boost 1.54.0 and 1.55.0.

Veda
  • 2,025
  • 1
  • 18
  • 34

2 Answers2

1

boostAny2 is a pointer to boost::any. You pass it as parameter to check, which expects a boos::any, so a new boost::any instance is created from the boost::any* (ie. the value type will be boost::any*). Ref. https://www.boost.org/doc/libs/release/doc/html/boost/any.html

Or in other words, what's actually happening is (conceptually) :

boost::any* boostAny2 = &boostAny;
boost::any param = boost::any(boostAny2); // contruct a new boost::any instance from the pointer boostAny2
check(param);

Maybe you meant instead :

check(*boostAny2);

The same applies to boostAny3.

Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40
1

You are implicitly constructing any objects containing the pointers you supplied, so obviously they aren't empty.

Your code

check(boostAny3);

is equivalent to this code

check(any(boostAny3));

I think what you want instead is

check(*boostAny3);
john
  • 85,011
  • 4
  • 57
  • 81