Under what conditions does C++ optimize out constructor calls?

前端 未结 1 815
萌比男神i
萌比男神i 2021-01-13 21:15

I\'m writing a class for Matrix arithmetic, and one feature I\'m implementing is that you can \"slice\" a matrix and get another matrix back, but done such that the returned

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 21:30

    This is called copy elision, or return value optimization (§12.8.31 of the C++11 standard). The copy constructor can be skipped for virtually any function that returns a class type. This is often closely related to the actual implementation of returning class types. (Note that you're sort of relying on this too: presumably slice returns your matrix type by value, and you don't want a copy constructor called there if it would break your aliasing.)

    You'll most likely need to implement this in some other way—for example, slice returning some kind of proxy type that supports the same operations and can convert to your normal matrix type, breaking aliasing during that conversion.

    0 讨论(0)
提交回复
热议问题