Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the argument of the copy constructor a reference rather than a pointer?

Why is the argument of the copy constructor a reference rather than a pointer?

Why can't we use the pointer instead?

like image 533
Aquarius_Girl Avatar asked Sep 04 '13 10:09

Aquarius_Girl


People also ask

Why argument to a copy constructor must be passed as a reference?

It is necessary to pass object as reference and not by value because if you pass it by value its copy is constructed using the copy constructor. This means the copy constructor would call itself to make copy. This process will go on until the compiler runs out of memory.

Why reference is used in copy constructor and not pointer?

Passing by references ensures an actual object is passed to the copy constructor, whilst a pointer can have NULL value, and make the constructor fail.

Why do you have to pass the argument to a copy constructor as a reference Mcq?

Explanation: This is mandatory to pass the object by reference. Otherwise, the object will try to create another object to copy its values, in turn a constructor will be called, and this will keep on calling itself. This will cause the compiler to give out of memory error.


1 Answers

There are many reasons:

  1. References cannot be NULL. OK, it's possible to create a NULL reference, but it's also possible to cast a std::vector<int>* into a std::vector<SomeType>*. That doesn't mean such a cast has defined behavior. And neither does creating a NULL reference. Pointers have defined behavior when set to NULL; references do not. References are therefore always expected to refer to actual objects.

  2. Variables and temporaries cannot be implicitly converted into pointers to their types. For obvious reasons. We don't want pointers to temporaries running around, which is why the standard expressly forbids doing it (at least when the compiler can tell you are doing it). But we are allowed to have references to them; these are implicitly created.

  3. Because of point number 2, using pointers rather than references would require every copy operation to use the address-of operator (&). Oh wait, the C++ committee foolishly allowed that to be overloaded. So any copy operation would need to actually use std::addressof, a C++11 feature, to get the address. So every copy would need to look like Type t{std::addressof(v)}; Or you could just use references.

like image 66
Nicol Bolas Avatar answered Oct 04 '22 16:10

Nicol Bolas