假设一个函数具有以下原型(prototype)
template<typename T>
std::unique_ptr<T> process_object(std::unique_ptr<T> ptr);
该函数可能返回( move 版本)传递给它的对象,或完全不同的对象。
如下使用这个函数,C++合法吗?
std::unique_ptr<Widget> pw(new Widget());
pw = process_object(std::move(pw));
如果我没记错的话,有一条 C/C++ 规则禁止在单个完整表达式中多次修改对象。这条规则在这里适用吗?如果是的话,有什么方法可以在一行中以不同的方式表达这个成语吗?
如果将 std::unique_ptr
替换为被鄙视的 std::auto_ptr
会怎样?
最佳答案
Is it legal C++ to use this function as follows?
是的,没关系。
If I remember correctly, there is a C/C++ rule that forbids modifying an object more than once in a single full expression.
不完全是。您不能多次修改一个对象(或修改它并使用它的值)进行无序访问。
Does this rule apply here?
没有。评估函数参数在函数调用之前排序,函数调用在赋值之前排序。所以这两个访问是有序的,一切都很好。
关于c++ - 允许在一个完整表达式中 move 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28111882/