`std :: any_cast`返回一个副本 [英] `std::any_cast` returns a copy

查看:261
本文介绍了`std :: any_cast`返回一个副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读文档,我发现奇怪的是,API强制转换将值返回到保留的对象或指向该对象的指针.为什么不返回参考?每次使用非指针类型参数调用函数时,都需要复制一个副本.

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

推荐答案

您可以在此处查看有关C ++标准的讨论:

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 _casts in C++.

这篇关于`std :: any_cast`返回一个副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆