user1056903
user1056903

Reputation: 941

Using of Smart Pointers on objects with automatic storage duration

Is it a problem if I apply Smart Pointers (scoped_ptr, unique_ptr or shared_ptr) on objects with automatic storage duration (i.e. stored on the stack)? I assume not as in both cases (with and without smart pointers) they will be deleted if no more pointers pointing on them. Pointers themself have always automatic storage duration, i.e. they will be deleted if they go out of scope.

Upvotes: 2

Views: 454

Answers (3)

Saurav Sahu
Saurav Sahu

Reputation: 13934

Here is the demo :

class Foo{
    public:
        Foo(){cout << "Foo created!\n";}
        ~Foo(){cout << "Foo destroyed!\n";}
};
void go(){
    Foo foo;
    cout << "Position A\n";
    {
        Foo foo1;
    }
    cout << "Position B\n";
    {
        Foo *foo2;
    }
    cout << "Position C\n";
    {
        Foo *foo3 = new Foo;
    }
    cout << "Position D\n";
    {
        std::shared_ptr<Foo> foo3(new Foo);
    }
    cout << "Position E\n";
    {
        std::shared_ptr<Foo> foo3(&foo);
    }
    cout << "Position F\n";
}

Gives output as:

Foo created!
Position A
Foo created!
Foo destroyed!
Position B
Position C
Foo created!
Position D
Foo created!
Foo destroyed!
Position E
Foo destroyed!

ends with

Runtime error: Error : free(): invalid pointer: 0x00007ffda60f0e67

Notice the difference between Positions D-E and Positions E-F (deleting a pointer that didn't come from new, so results in undefined behavior).

Upvotes: 2

MikeMB
MikeMB

Reputation: 21156

Yes it is a problem as the smart pointer will (ignoring custom deleters for now) call delete on an object that was not created via new (which is UB) and the destructor will be called twice (which results in undefined behavior too).

It will btw. also lead to errors if you try to manage an object via two independent smart pointers.

So, where lifetime management is concerned, "The more the merrier" is definitely not true.

Upvotes: 1

bolov
bolov

Reputation: 75697

Yes, there is a problem (a big one): you are using smart pointers to do something (I don't know what) they were not designed to do. They are meant to manage the lifetime of dynamically allocated objects. They solve a problem inherited from C, they offer ownership to objects which need dynamic allocation/release (they aren't restricted to memory (pointers); you can actually use smart pointers to manage any type of resource which needs acquire/release, e.g. system resources, file descriptors, etc).

Ok, but aside from the philosophical problem, is there a practical problem?

Yes!!. A smart pointer will call delete / delete[] on the owned object, which is Undefined Behavior when the pointer is not obtained from new / new[] respectively.

And yes, you can use a custom deleter that does nothing, but then what was the point of using smart pointers anyway?

Upvotes: 5

Related Questions