【发布时间】:2020-05-15 10:56:27
【问题描述】:
考虑以下程序:
#include <functional>
#include <iostream>
class RvoObj {
public:
RvoObj(int x) : x_{x} {}
RvoObj(const RvoObj& obj) : x_{obj.x_} { std::cout << "copied\n"; }
RvoObj(RvoObj&& obj) : x_{obj.x_} { std::cout << "moved\n"; }
int x() const { return x_; }
void set_x(int x) { x_ = x; }
private:
int x_;
};
class Finally {
public:
Finally(std::function<void()> f) : f_{f} {}
~Finally() { f_(); }
private:
std::function<void()> f_;
};
RvoObj BuildRvoObj() {
RvoObj obj{3};
Finally run{[&obj]() { obj.set_x(5); }};
return obj;
}
int main() {
auto obj = BuildRvoObj();
std::cout << obj.x() << '\n';
return 0;
}
clang 和 gcc (demo) 都输出 5 而不调用复制或移动构造函数。
这种行为是否得到 C++17 标准的良好定义和保证?
【问题讨论】:
-
"现在需要复制省略" 那是not how it works。您的代码中没有保证省略。
-
我应该使用什么术语来描述演示中观察到的行为?
标签: c++ destructor raii copy-elision rvo