...
| Code Block |
|---|
|
class Widget {
// ...
};
class Thingy {
public:
// ...
Thingy& operator=(const Thingy& rhs);
// ...
private:
Widget *w;
};
// ...
Thingy& Thingy::operator=(const Thingy& rhs) {
delete w; // delete the current Widget
w = new Widget(*rhs.w); // create a copy of rhs's Widget
return *this;
}
// ...
|
...
| Code Block |
|---|
|
Thingy& Thingy::operator=(const Thingy& rhs) {
if (this != &rhs) {
delete w;
w = new Widget(*rhs.w);
}
return *this;
}
|
...
| Code Block |
|---|
|
Thingy& Thingy::operator=(const Thingy& rhs) {
Widget *original = w;
w = new Widget(*rhs.w);
delete original;
return *this;
}
|
...
| Code Block |
|---|
|
class Thingy {
public:
// ...
// compiler-generated copy assignment now correct
private:
std::tr1::shared_ptr<Widget>ptr<Widget> w;
};
|
This version of the code is also exception-safe, because the implementation of shared_ptr is exception-safe.
...
| Wiki Markup |
|---|
\[[Meyers 05|AA. C++ References#Meyers 05]\] Item 11: Handle assignment to self in {{operator=}}. |
...
RES35-C. Declare a copy constructor, a copy assignment operator, and a destructor in a class that manages resources 08. Memory Management (MEM) RES37-C. Release resources that require paired acquire and release in the object's destructor