我想验证以下优化是否按预期起作用:
- RVO
- 命名的RVO
- 通过值传递参数时的拷贝省略
所以我写了这个小程序:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <vector>
struct Foo {
Foo(std::size_t length, char value) : data(length, value) { }
Foo(const Foo & rhs) : data(rhs.data) { std::cout << "*** COPY ***" << std::endl; }
Foo & operator= (Foo rhs) {
std::cout << "*** ASSIGNMENT ***" << std::endl;
std::swap(data, rhs.data); // probably expensive, ignore this please
return *this;
}
~Foo() { }
std::vector<char> data;
};
Foo TestRVO() { return Foo(512, 'r'); }
Foo TestNamedRVO() { Foo result(512, 'n'); return result; }
void PassByValue(Foo inFoo) {}
int main()
{
std::cout << "\nTest RVO: " << std::endl;
Foo rvo = TestRVO();
std::cout << "\nTest named RVO: " << std::endl;
Foo named_rvo = TestNamedRVO();
std::cout << "\nTest PassByValue: " << std::endl;
Foo foo(512, 'a');
PassByValue(foo);
std::cout << "\nTest assignment: " << std::endl;
Foo f(512, 'f');
Foo g(512, 'g');
f = g;
}
我开启了优化选项进行编译:
$ g++ -o test -O3 main.cpp ; ./test
这是输出结果:
Test RVO:
Test named RVO:
Test PassByValue:
*** COPY ***
Test assignment:
*** COPY ***
*** ASSIGNMENT ***
根据输出,RVO和已命名的RVO符合预期。然而,在赋值运算符和调用PassByValue
时,不执行拷贝省略操作。
用户定义的复制构造函数是否不允许拷贝省略?(我知道RVO明确允许,但我不知道通过值传递时是否允许拷贝省略。)有没有一种方法可以在不定义复制构造函数的情况下验证拷贝省略?