开发者

No call to the copy constructor [duplicate]

开发者 https://www.devze.com 2023-01-27 09:07 出处:网络
This question a开发者_开发技巧lready has answers here: Why copy constructor is not called in this case?
This question a开发者_开发技巧lready has answers here: Why copy constructor is not called in this case? (4 answers) Closed 9 years ago.

Consider the given code

struct ABC
{
    ABC()
    {
        std::cout<<" Calling from default constructor";
    }

    ABC(const ABC &copy)
    {
        std::cout<<"Calling from copy constructor";
    }
};

int main()
{
    ABC abc = ABC();
}

I have two questions


Q1) Removing const from the copy constructor parameter declaration gives error. Why?

Q2) After adding the const keyword I dont see a call to the copy constructor. Why? The copy constructor does not get called so why is the const necessary?


TIA


  1. You need the const because you try to initialize abc with a temporary ABC() which is const. Hence if the constructor is not const the compiler must reject the code.

  2. After you make it const the code is standard complaint and the compiler can compile it. However it's allowed to optimize out the copy in this case as said in the standard, so it removes the call to the copy constructor.


Q1) Removing const from the copy constructor parameter declaration gives error. Why?

ABC abc = ABC();

is equivalent to

ABC abc((ABC()));

Since you are passing a temporary to the copy constructor, it can only bind to const references, not non-const references.

A copy constructor can take non-const references (e.g std::auto_ptr), but this means their usage is more restricted.

Q2) After adding the const keyword I dont see a call to the copy constructor. Why? The copy constructor does not get called so why is the const necessary?

In the given scenario the compiler is allowed to optimize redundant calls to constructor away. Why create a default object only to copy it, if it could just invoke the default constructor alone?

However, even if calls to copy constructor are optimized away, the compiler has to check that the code would be valid as written - as if the copy construction was not optimized away.


The const is necessary since you are not allowed to bind a temporary to a non-const reference. Even though the compiler optimizes away the copy constructor, that is not until a latter stage.

The C++ 0x standard is addressing this with the addition of rvalue references. which would allow you to drop the const parameter to a non-const...

ABC( ABC&& copy) 

Although you would still want the regular reference copy constructor...


If you also define the assignment operator you'll see that not even that one gets called: compiler optimizes ABC abc = ABC(); in ABC abc;, since they've got the same semantics.

About the other doubt, G++ doesn't complain about declaring copy constructor parameter as non-const (not even with -Wall -W -std=c++98). Didn't check out the standard about this anyway.

0

精彩评论

暂无评论...
验证码 换一张
取 消