yohhoyの日記

技術的メモをしていきたい日記

copy elision抑止オプション

gcc(g++)において、C++言語仕様で許容されているcopy elision*1を明示的に抑止するオプション。

-fno-elide-constructors
 The C++ standard allows an implementation to omit creating a temporary that is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.

Using the GNU Compiler Collection (GCC) - 3.5 Options Controlling C++ Dialect

2023-12-13追記:C++17以降は 値のコピー省略(RVO)が保証される よう言語仕様が改訂された。下記サンプルコードに対して-fno-elide-constructorsオプション指定を行ってもコピーコンストラクタは呼び出されない。

#include <iostream>

struct X {
  X() { std::cout << "X()" << std::endl; }
  X(const X&) { std::cout << "X(const X&)" << std::endl; }
};

X f()
{ return X(); }

int main()
{
  X x = f();
}

gcc 4.6.3での実行結果:

$ g++ input.cpp; ./a.out
X()

$ g++ input.cpp -fno-elide-constructors; ./a.out
X()
X(const X&)
X(const X&)

*1:"copy elision" は俗に言われる "名前付き戻り値最適化(NRVO; named return value optimization)" または "戻り値最適化(RVO; return value optimization)" を包含する。