关于返回值中复制构造函数的问题

问题描述 投票:0回答:1

这是来自this的代码测试。 我复制了其中一些如下:

//struct definition. All kinds of prints
struct Snitch {   // Note: All methods have side effects
  Snitch() { cout << "c'tor" << endl; }
  ~Snitch() { cout << "d'tor" << endl; }

  Snitch(const Snitch&) { cout << "copy c'tor" << endl; }
  Snitch(Snitch&&) { cout << "move c'tor" << endl; }

  Snitch& operator=(const Snitch&) {
    cout << "copy assignment" << endl;
    return *this;
  }

  Snitch& operator=(Snitch&&) {
    cout << "move assignment" << endl;
    return *this;
  }
};
//end struct def

Snitch ReturnObj() {
  Snitch snit;
  cout<< "before return ReturnObj" << endl;
  return snit;  
}

int main() { 
  Snitch snitchobj1 = ReturnObj();  
  cout<< "end main" << endl;
}

我作为作者禁用了 RVO: g++ -fno-elide-constructors -o rvo.exe 。 vo_or_not.cpp 并运行 rvo.exe 以了解到底发生了什么。

我得到了:

c'tor
before return ReturnObj
move c'tor //I didn't know why this is move c'tor instead of copy c'tor
d'tor
move c'tor
d'tor
end main
d'tor

move c'tor 的第一次印刷对我来说是出乎意料的。台词“告密者snit;” in 函数定义了一个局部左值 snit 。那么返回时,应该调用复制构造函数来初始化临时对象吗?我对吗?或者它实际上是一个 xvalue 而不是一个 lvalue?

c++ c++17 move-semantics lvalue
1个回答
0
投票

当按值返回局部变量时,如果无法执行 named 返回值优化,编译器会更愿意将其移动到复制,就像您关闭 NRVO 后的情况一样 - 无法打开 RVO关闭,至少在严格一致性模式下关闭。

应该调用复制构造函数来初始化临时对象

我看不到任何临时物体。

© www.soinside.com 2019 - 2024. All rights reserved.