Piraha smart_ptr can't handle self assignment

Issue #1521 closed
Erik Schnetter created an issue

An assignment of the form

void foo(smart_ptr<T> x) {
  x = x;
}

will not work, since operator= assumes that LHS and RHS are different objects. The usual remedy is to add an if statement, doing nothing for self assignment.

Keyword:

Comments (10)

  1. Erik Schnetter reporter
    • removed comment

    This is not about parameter files, this is about C++ code. Writing "x=x" when x is a smart_ptr may accidentally delete the object to which x points, leading to segfaults.

  2. Steven R. Brandt
    • changed status to open
    • removed comment

    The patch is simple, but actually getting a segfault to trigger was a bit harder than I expected. #include <iostream> #include "smart_ptr.hpp"

    struct A { A() { std::cout << "Construct" << std::endl; } ~A() { std::cout << "Destruct" << std::endl; } // need virtual, otherwise no dereference occurs virtual void foo() { std::cout << "Foo" << std::endl; } };

    int main() { cctki_piraha::smart_ptr<A> y(new A(),false); y = y; y->foo(); return 0; }

  3. Erik Schnetter reporter
    • removed comment

    The patch is wrong; you need to skip both the clean() and inc() calls.

    I think that "if (this==&s) return *this;" as the first line of operator= should work.

    • if this and &s point to the same object, then the assignment operator is a no-op, so nothing needs to be done.
    • if the pointers are different, but their guts are the same, then dec/inc should not matter since there are at least two pointers.
  4. Log in to comment