Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

class SomeClass
{
public:
    SomeClass(int meaningless){}

    SomeClass(const SomeClass& sc)
    {
        cout << "Copy Constructor invoked!" << endl;
    }
};

int main()
{
    SomeClass test(SomeClass(9999));  // Copy constructor not invoked. 
}

I think this has nothing to do with RVO since I am not returning any values.

More interesting, when I make the copy constructor private, the compiler wouldn't even compile even if it omit the copy constructor.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
342 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...