I was reading the documentation for std::any_cast
and I find it strange that the API has the cast either return a value to the held object or a pointer to it. Why not return a reference? A copy needs to be made every time the function is called with a non pointer type argument.
I can see that the pointer version of the cast might signal intentions a bit more and might be a bit more clear but why not have the value returned be a reference like this?
template<typename ValueType>
ValueType& any_cast(any* operand);
instead of
template <typename ValueType>
ValueType* any_cast(any* operand);
Further it seems like even if you ask for a reference the cast removes the reference and returns a copy to the stored object see the explanations for the return values for function overloads 1-3 here http://en.cppreference.com/w/cpp/utility/any/any_cast
nullptr
? It can't be dereferenced to satisfy a returned reference. I think what you are really asking about is why the overloads ofany_cast
that take a reference as input return a copy instead of a reference as output, isn't that right? – Copyboyany_cast
gives a reference if you tell it to. This is like sayingstatic_cast
always returns a copy. – Mickeymickiany_cast<Something&>
you will still get a copy when you pass a reference to anstd::any
object – Chaldeanany_cast<Something&>
will remove the reference while working on the object internally, but it still returnsSomething&
as output. – Copyboy