C++ Copy Generator Parameters

Asked 2 years ago, Updated 2 years ago, 20 views

Is there any reason to receive it as a reference? I think it's a forced appointment.

c++

2022-09-21 19:38

1 Answers

If there is a class called A, A(const A&obj) is defined by the standard as a copy constructor.

https://en.cppreference.com/w/cpp/language/copy_constructor

To look at it logically, A(Aobj) a copy generator.

A a;
A b = a;

When b is made into a copy constructor, A(Aobj) is not a reference, obj requires copying from a to obj. The copy must then be made again, and the copy generator will be called. This puts you in a recursive situation where the copy generator is called again for that copy generator. This recursive cannot escape forever. Objects entered as copy constructors must not be copied as parameters.

A(const A& obj), the copy for A is not required and the copy constructor does not need to be called because the address is moved, not the copy of the object, when passed from a to obj. Therefore, the copy constructor for Ab = a; should be able to perform it immediately.


2022-09-21 19:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.