以下のコードを書きました.私は X 型のオブジェクトを4回作っているつもりです.
C++
1class X 2{ 3public: 4 int v = -99; 5 static int nctorCalled; 6 static int ndtorCalled; 7 8 ~X(){ ++ndtorCalled; } 9 10 X( int v=0 ) : v{v} { ++nctorCalled; std::cout << "int" << std::endl; } 11 X( const X &ref ){ ++nctorCalled; v=ref.v+10; std::cout << "const &" << std::endl; } 12 X( X &&ref ){ ++nctorCalled; v=ref.v+100; std::cout << "&&" << std::endl; } 13}; 14int X::nctorCalled = 0; 15int X::ndtorCalled = 0; 16 17inline void ShowV( const X &x ){ std::cout << " " << x.v << "\n" << std::endl; } 18 19// 20int main( /*int argc, const char *argv[]*/ ) 21{ 22 { 23 X x1{1}; 24 ShowV(x1); 25 26 X x2{ x1 }; 27 ShowV(x2); 28 29 X x3{ X{4} }; 30 ShowV(x3); 31 } 32 33 std::cout << X::nctorCalled << std::endl; 34 std::cout << X::ndtorCalled << std::endl; 35 36 return 0; 37}
しかしながら,出力は以下となりました.
X x3{ x{4} };
のところの X{4}
が 4
に置き換えられてしまっている(そして,そのためにオブジェクトの生成回数が3回になってしまっている)ように見えます.
何故ですか?
text
1int 2 1 3 4const & 5 11 6 7int 8 4 9 103 113
[補足]
Visual Studio 2017 で実行しました.
何らかの最適化の結果なのか?と思ったのですが,プロジェクトのプロパティで最適化の設定は「無効(/Od)」となっています.
※本件のタイトルは「オブジェクトが生成されない?」として「?」を付けたかったのですが,それだと何故か投稿できなかったので,現状の(断定気味な感じの)タイトル文言になっています.
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/08/31 04:28
2022/08/31 09:20
2022/08/31 10:33