Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`std::any_cast` returns a copy

Tags:

c++

c++17

stdany

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

like image 617
Curious Avatar asked Jan 28 '17 02:01

Curious


People also ask

What does any_ cast do?

Anycast is a network addressing and routing method in which incoming requests can be routed to a variety of different locations.

Is std:: any slow?

Performance of std::any Also, invoking a std::any_cast to retrieve the value is quite slow compared to std::variant . The Boost equivalent of std::any , boost::any , provides a fast version of std::any_cast called boost::any_cast_unsafe which can be utilized if you know which type is contained.

Does std:: any allocate memory?

Here are the things to remember about std::any : std::any is not a template class. std::any uses Small Buffer Optimization, so it will not dynamically allocate memory for simple types like ints, doubles… but for larger types it will use extra new .


1 Answers

You can see a discussion regarding the C++ standard for this here: https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/ngSIHzM6kDQ

Note that Boost has defined any_cast this way for more than a decade, plus it matches static_cast and friends. So if you want a reference, do this:

any_cast<Foo&>(x)

The same as you'd do for the older _casts in C++.

like image 134
John Zwinck Avatar answered Sep 18 '22 15:09

John Zwinck