`std::any_cast` returns a copy

瘦欲@ 提交于 2019-12-07 04:58:58

问题


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


回答1:


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++.



来源:https://stackoverflow.com/questions/41905868/stdany-cast-returns-a-copy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!