C ++ 11:在参数列表上调用std :: move() [英] C++11: std::move() call on arguments' list
问题描述
在该对象上还调用了std :: move()时,可以安全地对参数列表中的对象进行操作吗?
Is it safe to operate on object within arguments' list, when there is also std::move() invoked on that object ?
void foo(int* raw, std::unique_ptr<int> u)
{
*raw = 456;
}
std::unique_ptr<int> p(new int(123));
foo(p.get(), std::move(p));
如果将std :: move(p)评估为第一个参数,foo()中的"raw"指针是否有效?
Will the `raw' pointer in foo() be valid if std::move(p) was evaluated as the first parameter ?
推荐答案
否,不是安全的.参数的评估顺序在标准中未指定 .因此,您的代码 可以运行为:
No, it's NOT safe. the eval order of argument is not specified in standard. So your code can be run as:
-
std::move(p)
. - 调用
std::unique_ptr<int>
的move构造函数. -
p.get()
(由于2,将是nullptr
.)并传递此参数. - 致电
foo
.
std::move(p)
.- call move constructor of
std::unique_ptr<int>
. p.get()
(because of 2., this will benullptr
.) and pass this parameter.- call
foo
.
您必须这样做:
int *raw = p.get();
foo(raw, std::move(p));
请注意,您的代码可以很好地工作,因为某些编译器可以将您的代码编译为3-> 1-> 2->4.但是,这并不意味着代码是安全的.没有指定标准> o<
Notice that your code can work well, because some compilers can compile your code into 3 -> 1 -> 2 -> 4. However, it doesn't mean code is safe. it's not specified standard >o<
这篇关于C ++ 11:在参数列表上调用std :: move()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!