Rahul wrote:
Quote:
Hi Everyone,
>
It is well known that the input parameter which is passed to the
copy constructor is passed as reference and not as as object. Because
passing an object is as good as making another copy which in itself
needs a copy constructor.
>
However i was wondering why can't the existing object be passed as
a pointer instead of a reference to the copy constructor which creates
a new object.
a) You _can_ define a constructor
T ( T* ptr )
: member_1 ( ptr->member_1 )
, ...
{}
Although it will buy you nothing but trouble since you invite all the perils
of undefined behavior upon you, should you pass a null pointer.
b) Such a constructor is _not_ a copy constructor. The standard defines copy
constructors as those that conform to certain signatures. Also, the
standard says that at certain points copy constructors will be used, say,
to create temporaries. That the constructor in (a) is not a copy
constructor has therefore the consequence that it will not be considered
for such purposes.
That the copy-constructor is invoked automatically in certain contexts and
can be optimized away in others creates a restriction on its semantics: it
really better just construct a copy of the object. Thus, one problem with
making (a) a valid signature for copy-constructors is that it renders it
impossible to use a constructor like (a) for other purposes. E.g. a
single-linked list might have a private constructor
List ( List* tail_ptr = 0, ValueType const & value = ValueType() )
Best
Kai-Uwe Bux