Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider (sch jbop) (X_X)@==(Q_Q)@

...

Code Block
bgColor#FFcccc
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;
}
// ...

If this copy assignment operator is used in a self-assignment, the delete operator not only deletes the Widget of the current object, it also deletes rhs's Widget, resulting in the Thingy containing a pointer to a deleted object!

...

Code Block
bgColor#ccccff
class Thingy {
    public:
        // ...
        // compiler-generated copy assignment now correct
    private:
        std::tr1::shared_ptr<Widget> w;
};

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

RES36-C

1 (low)

2 (probable)

1 (high)

P2

L3

References

Wiki Markup
\[[Henricson 97|AA. C++ References#Henricson 97]\] Rule 5.12 Copy assignment operators should be protected from doing destructive actions if an object is assigned to itself.

Wiki Markup
\[[Meyers 05|AA. C++ References#Meyers 05]\] Item 11: Handle assignment to self in {{operator=}}.