简体   繁体   中英

Boost::any not empty when used from a pointer

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.

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 .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM