C ++ 11:在参数列表上调用std :: move() [英] C++11: std::move() call on arguments' list

查看:82
本文介绍了C ++ 11:在参数列表上调用std :: move()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在该对象上还调用了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:

  1. std::move(p).
  2. 调用std::unique_ptr<int>的move构造函数.
  3. p.get()(由于2,将是nullptr.)并传递此参数.
  4. 致电foo.
  1. std::move(p).
  2. call move constructor of std::unique_ptr<int>.
  3. p.get() (because of 2., this will be nullptr.) and pass this parameter.
  4. 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屋!

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