Search code examples
c++boostboost-any

Does boost::any save a copy or reference/pointer?


Is the following code safe?

boost::any any_value;

{
    std::string s = "HelloWorld";
    any_value = s;
}

std::string ss = any_cast<std::string>(any_value);

Solution

  • From Boost.Any docs:

    template<typename ValueType> any & operator=(const ValueType & rhs);
    

    Makes a copy of rhs, discarding previous content, so that the new content of is equivalent in both type and value to rhs.

    So yes, it's safe to do that. A copy of the string is stored, not a reference to it.