开发者

copy-constructor related question (native c++) [duplicate]

This question already has answers here: 开发者_JAVA技巧 Closed 11 years ago.

Possible Duplicate:

Why should the copy constructor accept its parameter by reference in C++?

i know that a copy constructor must have a reference as a parameter, to avoid an 'infinite number of calls' to itself. my question is - why exactly that happens, what is the logic behind it?

CExample(const CExample& temp)
{
   length = temp.length;
}


assume your argument to the copy C'tor was passed by value, the first thing the C'tor would have done, was copying the argument [that's what every function, including constructors do with by-value arguments]. in order to do so, it would have to invoke the C'tor again, from the original to the local variable... [and over and over again...] which will eventually cause an infinite loop.


Copy constructors are called on some occasions in C++. One of them is when you have a function like

void f(CExample obj)
{
    // ...
}

In this case, when you make a call

CExample x;
f( x );

CExample::CExample gets called to construct obj from x.

In case you have the following signature

void f(CExample &obj)
{
     // ...
}

(note that obj is now passed by reference), the copy constructor CExample::CExample does not get called.

In the case your constructor accepts the object to be copied by value (as with the function f in the first example), compiler will have to call the copy constructor first in order to create a copy (as with the function f, again), but... oops, we have to call the copy constructor in order to call the copy constructor. This sounds bad, doesn't it?


See here

"It is a reference because a value parameter would require making a copy, which would invoke the copy constructor, which would make a copy of its parameter, which would invoke the copy constructor, which ... "

Or put a different way a value parameter to the constructor would have to call the constructor to copy the value in the parameter. This new constructor would need to do the same - leading to infinite recursion!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜