省略复制及移动 (C++11 起)构造函数,导致零复制的按值传递语义。
举个例子:
#include <bits/stdc++.h> using namespace std; struct A { A() { cout << "construct" << endl; } A(const A&) { cout << "copy construct" << endl; } A(A&&) { cout << "move construct" << endl; } int i; }; A fun() { return A(); } int main() { A a = fun(); return 0; }
输出结果为:
construct
如果关闭返回值优化(-fno-elide-constructors )则输出结果为:
construct
move construct
move construct
以上construct发生在return 语句上的A(),在函数的返回对象上一次move construct,在main函数中一次move construct。
强制的复制/移动操作消除:要求编译器省略类的复制和移动构造,直接构造在它们要复制/移动的内存上去:
主要是在return语句中(见以上)或初始化(如以下)时:
A x = A(A(fun()));
输出结果为(注意此时需要存在move construct/copy construct(默认存在),需要访问权限,虽然没有使用):
construct
关闭优化时的输出结果为:
construct
move construct
move construct
move construct
move construct
以上是在c++11下,改为c++17(-std=c++17 -fno-elide-constructors)输出结果两种都为:
construct
c++17规定不再有用以复制/移动的临时量。描述 C++17 语义的另一种方式是“传递未实质化的值”:返回并使用纯右值时不实质化临时量。
return 语句中,当操作数是拥有自动存储期的非 volatile 对象的名字,其并非函数形参或 catch 子句形参,且其具有与函数返回类型相同的类类型(忽略 cv限定)时。这种复制消除的变体被称为 NRVO,“具名返回值优化 (named return value optimization)”。
在c++17前,在对象的初始化中,当源对象是无名临时量且与目标对象具有相同类型(忽略 cv限定)时。当无名临时量为 return 语句的操作数时,称这种复制消除的变体为 RVO,“返回值优化 (return value optimization)”。
返回值优化是强制要求的,而不再被当做复制消除;见上文。
#include <bits/stdc++.h> using namespace std; struct A { constexpr A(...) : p(this) {} // A(const A&) { // cout << "copy construct" << endl; // } // A(A &&) { // cout << "move construct" << endl; // } void *p; }; constexpr A fun() { A a; return a; } constexpr A a; // a.p -> a // constexpr A b = fun() // error: b.p -> temp A c = fun(); // c.p -> temp extern const A d; constexpr A foo() { A e; if (&e == &d) { return A(); } else { return e; } } void print() { auto a = foo(); cout << &a << "-" << a.p << endl; cout << &c << "-" << c.p << endl; } int main() { print(); return 0; }
输出结果为:
0x7ffee40f37a8-0x7ffee40f3780 0x10bb0f0d0-0x7ffee40f22a0
cppreference示例:
#include <bits/stdc++.h> using namespace std; struct Noisy { Noisy() { std::cout << "constructed\n"; } Noisy(const Noisy&) { std::cout << "copy-constructed\n"; } Noisy(Noisy&&) { std::cout << "move-constructed\n"; } ~Noisy() { std::cout << "destructed\n"; } }; std::vector<Noisy> f() { std::vector<Noisy> v = std::vector<Noisy>(3); // 从临时量 (C++17 前) // 从纯右值 (C++17 起) // 初始化 v 中的复制消除 return v; // 从 v 到结果对象的 NRVO(C++17 中仍不保证) } // 若禁用优化,则调用移动构造函数 void g(std::vector<Noisy> arg) { std::cout << "arg.size() = " << arg.size() << '\n'; } int main() { std::vector<Noisy> v = f(); // 从 f() 返回的临时量 (C++17 前) // 从纯右值 f() (C++17 起) // 初始化 v 中的复制消除 g(f()); // 从 f() 返回的临时量 (C++17 前) // 从纯右值 f() (C++17 起) // 初始化 g() 的形参中的复制消除 }
可能的输出:
constructed constructed constructed constructed constructed constructed arg.size() = 3 destructed destructed destructed destructed destructed destructed