gpt4 book ai didi

c++ - move 或命名返回值优化 (NRVO)?

转载 作者:IT老高 更新时间:2023-10-28 12:47:51 36 4
gpt4 key购买 nike

假设我们有以下代码:

std::vector<int> f()
{
std::vector<int> y;
...
return y;
}

std::vector<int> x = ...
x = f();

似乎编译器在这里有两种方法:

(a) NRVO:破坏 x,然后构造 f() 代替 x。
(b) move :在临时空间中构造 f(),将 f() move 到 x 中,销毁 f()。

根据标准,编译器可以自由使用这两种方法吗?

最佳答案

编译器可以 NRVO 进入临时空间,或将构造 move 到临时空间。从那里它会 move assign x.

更新:

任何时候您想使用右值引用进行优化,但您对结果不满意,请为自己创建一个跟踪其状态的示例类:

  • 构造
  • 默认构造
  • 搬来
  • 销毁

并通过您的测试运行该类(class)。例如:

#include <iostream>
#include <cassert>

class A
{
int state_;
public:
enum {destructed = -2, moved_from, default_constructed};

A() : state_(default_constructed) {}
A(const A& a) : state_(a.state_) {}
A& operator=(const A& a) {state_ = a.state_; return *this;}
A(A&& a) : state_(a.state_) {a.state_ = moved_from;}
A& operator=(A&& a)
{state_ = a.state_; a.state_ = moved_from; return *this;}
~A() {state_ = destructed;}

explicit A(int s) : state_(s) {assert(state_ > default_constructed);}

friend
std::ostream&
operator<<(std::ostream& os, const A& a)
{
switch (a.state_)
{
case A::destructed:
os << "A is destructed\n";
break;
case A::moved_from:
os << "A is moved from\n";
break;
case A::default_constructed:
os << "A is default constructed\n";
break;
default:
os << "A = " << a.state_ << '\n';
break;
}
return os;
}

friend bool operator==(const A& x, const A& y)
{return x.state_ == y.state_;}
friend bool operator<(const A& x, const A& y)
{return x.state_ < y.state_;}
};

A&& f()
{
A y;
return std::move(y);
}

int main()
{
A a = f();
std::cout << a;
}

如果有帮助,请将打印语句放在您感兴趣的特殊成员中(例如,复制构造函数、 move 构造函数等)。

顺便说一句,如果您遇到此段错误,请不要担心。它对我来说也是段错误。因此,这种特殊设计(返回对局部变量的右值引用)不是一个好的设计。在您的系统上,它可能会打印出“A is destructed”,而不是段错误。这将是您不想这样做的另一个迹象。

关于c++ - move 或命名返回值优化 (NRVO)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6233879/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com