我目前对 C++17 保证的 RVO 及其含义感到非常困惑。我知道要启动 NRVO,我需要确保
通过函数的所有可能返回路径返回一个对象的同一个实例,并且
在调用端使用函数调用初始化关联对象
考虑一个最简单的装饰类 Widget,我想分配一对没有副本的 Widget,然后返回它
#include<iostream>
#include<utility>
struct Widget {
Widget() { std::cerr << "Default ctor" << std::endl; }
explicit Widget(int i) { std::cerr << "custom ctor" << std::endl; }
Widget(Widget const &) { std::cerr << "copy ctor" << std::endl; }
Widget(Widget &&) { std::cerr << "move ctor" << std::endl; }
Widget &operator=(Widget const &) { std::cerr << "copy assign" << std::endl; }
Widget &operator=(Widget &&) { std::cerr << "move assign" << std::endl; }
int i_;
};
auto foo(){
std::pair<Widget,Widget> w; // default construction
auto &[w1,w2] = w;
// do something with w1 and w2
return w;
}
int main(){
auto f = foo();
}
没有复制,但现在我尝试使用 make_pair
auto foo(){
auto w = std::make_pair<Widget,Widget>({},{}); // Awkward syntax and move construction
auto &[w1,w2] = w;
// do something with w1 and w2
return w;
}
如果我想使用 make_pair,这真的是唯一可能的选择吗?与第一个功能相比,为什么要涉及移动构造?