开发者

copy constructor in c++ [duplicate]

开发者 https://www.devze.com 2023-02-17 02:46 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Why should the copy constructor accept its 开发者_StackOverflow中文版parameter by reference in C++?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why should the copy constructor accept its 开发者_StackOverflow中文版parameter by reference in C++?

why do we have have a reference always in a copy constructor?

if there is a class:

class Base{};

its copy constructor is:

Base::Base(const Base& B);

why is always a reference as the argument?


Had it not been a reference, the compiler would need to invoke the copy constructor in order to pass the parameter to the copy constructor.

That would result in a

copy constructor in c++ [duplicate]


(source: prodeveloper.org)
.


If you tried to pass the parameter by value the compiler would have to copy the parameter and that would again invoke the copy constructor. This would lead to endless recursion and stack overflow.


copy-constructor is called when there is a need of making a copy of your object.

Now think, if the copy-constructor doesn't take reference of the object, that means you've to pass it by value that in turn would require making a copy of your original object. That means, it'll again call copy-constructor, to make a copy of the object. In this way, it'll keep on calling copy-constructor.

0

精彩评论

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