Copy constructor elision?

后端 未结 2 1263
挽巷
挽巷 2020-12-03 23:48

Don\'t quite understand why this copy constructor is not invoked when I build with debug mode using VC2010.

class SomeClass
{
public:
    SomeClass(int meani         


        
相关标签:
2条回答
  • 2020-12-04 00:19

    It is an optimization done by the compiler. According to the language specification, the compiler is allowed to omit the call to the copy-constructor whenever it can.

    An accessible copy-constructor is needed for semantic check only, even though it is not actually called. Semantic check is done much before the optimization.

    However, if you compile it with -fno-elide-constructors option with GCC, then the copy-elision will not be performed, and the copy-constructor will be called. The GCC doc says,

    -fno-elide-constructors

    The C++ standard allows an implementation to omit creating a temporary which 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.

    With MSVC10, you can use /Od which according to the MSDN turns off all optimizations in the program.

    Note : Wikipedia has an article on copy elision

    0 讨论(0)
  • 2020-12-04 00:25

    According to the C++11 standard, §12.8.31:

    …This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):

    • when a temporary class object that has not been bound to a reference would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

    Temporary objects get a lot of leeway in C++, and compilers will be pretty aggressive when removing them. If your object had a lifetime of its own in any way, then the copy constructor would end up being called.

    However, I would definitely expect it to check the copy constructor's access modifier, though I can see an argument that you shouldn't (after all, you just aren't calling the copy constructor). But that probably wouldn't be very good practice, since copy elision is optional.

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