Constructor copy-related question (native C ++)

Possible duplicate:
Why does the copy constructor accept its parameter by reference in C ++?

I know that the copy constructor should have a link as a parameter in order to avoid the β€œendless number of calls” for itself. my question is: why exactly this happens, what is its logic?

CExample(const CExample& temp) { length = temp.length; } 
+4
source share
3 answers

Suppose your argument for a copy of C'tor was passed by value, the first thing C'tor would do was copy the argument [that every function, including constructors, has arguments by value). to do this, he would have to call C'tor again, from the original to the local variable ... [and again and again ...], which would eventually cause an infinite loop.

+6
source

Copy constructors are called in some cases 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 is called to build obj from x .

If you have the following signature

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

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

In the case when your constructor accepts an object to be copied by value (as is the case with the f function in the first example), the compiler will have to call the copy constructor first to create a copy (as with the f function, again), but .. oops, we must call the copy constructor to call the copy constructor. That sounds bad, right?

+2
source

See here

"This is a link because for the value parameter, you will need to create a copy that will call the copy constructor, which will make a copy of its parameter, which will reference the copy constructor, which ..."

Or else, enter the value parameter in the constructor to call the constructor to copy the value into the parameter. This new constructor will have to do the same, leading to infinite recursion!

+1
source

Source: https://habr.com/ru/post/1369477/


All Articles