すべきですが、うまくいきません(ライブの例)。コンパイラーは、コンストラクターの副作用を検出し、コピー省略を使用しないことを決定する場合があります。
#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