它应该,但我无法使它工作(现场示例)。编译器可能会检测到构造函数的副作用并决定不使用复制省略。
#include <iostream>
struct Range{
Range(double from, double to) : from(from), to(to) { std::cout << "Range(double,double)" << std::endl; }
Range(const Range& other) : from(other.from), to(other.to) { std::cout << "Range(const Range&)" << std::endl; }
double from;
double to;
};
struct Box{
Box(Range x, Range y) : x(x), y(y) { std::cout << "Box(Range,Range)" << std::endl; }
Box(const Box& other) : x(other.x), y(other.y) { std::cout << "Box(const Box&)" << std::endl; }
Range x;
Range y;
};
int main(int argc, char** argv)
{
(void) argv;
const Box box(Range(argc, 1.0), Range(0.0, 2.0));
std::cout << box.x.from << std::endl;
return 0;
}
编译运行:
clang++ -std=c++14 -O3 -Wall -Wextra -pedantic -Werror -pthread main.cpp && ./a.out
输出:
Range(double,double)
Range(double,double)
Range(const Range&)
Range(const Range&)
Box(Range,Range)
1