Re: overriding default copy-by-value semantics across a hierarchy of classes
Ron wrote:
On Jun 27, 2:07 pm, Paul Bibbings <paul.bibbi...@googlemail.com>
wrote:
Suppose I have two simple structs like A and B below ...
...snip...
... and I want to define a single base/derived hierarchy of classes
where the base, MyBase, maintains a private pointer to an instance of
A allocated on the heap, while MyDerived similarly maintains a
private pointer to a dynamically allocated instance of B.
MyBase& operator=(const MyBase& mb) {
if (this != &mb) {
delete a_ptr;
a_ptr = new A(*mb.a_ptr);
}
It is unclear to me since the A object is solely private to each
MyBase object
(really it could just be a member rather than a pointer to the
dynamically created
object), why you don't assign the two A parts here rather than making
a copy:
MyBase& operator=(const MyBase& mb) {
*a_ptr = mb.a_ptr;
return *this;
}
And that is wrong. The OP's version has the problem of not being
exception safe (suppose that creating the new object throws). And your's
leaks memory. A correct form of this idiom is:
MyBase& operator=(const MyBase& mb) {
A * temp = new A(mb.a_ptr);
delete a_ptr; // rid current pointed to object
a_ptr = temp;
return *this;
}
I.e. deep copy original to temporary pointer, remove object pointed to,
redirect pointer to new deep copy.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]