`std :: any_cast`返回一个副本 [英] `std::any_cast` returns a copy
问题描述
我正在阅读
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);
代替
template <typename ValueType>
ValueType* any_cast(any* operand);
更进一步,即使您要求提供引用,强制转换也会删除引用并返回副本到存储的对象,请参见此处有关函数重载1-3的返回值的说明
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
推荐答案
You can see a discussion regarding the C++ standard for this here: https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/ngSIHzM6kDQ
请注意,Boost用这种方法定义any_cast
已有十多年了,而且它与static_cast
和朋友匹配.因此,如果您需要参考,请执行以下操作:
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)
与您在C ++中使用较早的_cast
相同.
The same as you'd do for the older _cast
s in C++.
这篇关于`std :: any_cast`返回一个副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!