Search code examples
c++shared-ptr

Why can I modify an object through a raw pointer but not a shared_ptr?


So, I would like to use a function that modifies an object through a shared_ptr.

I've got this class Foo:

class Foo
{
private:
    bool i = false;

public:
    void activate()
    {
        i = true;
    }

    bool isActive()
    {
        return i;
    }
};

Nothing too fancy. My goal is to modify a Foo object through a pointer, like so:

Foo foo;

std::shared_ptr<Foo> ptrfoo = std::make_shared<Foo>(foo);
ptrfoo->activate();

// "foo.isActive" returns false here

Sadly, foo.isActive returns false when I want it to return true. But the thing is, it works with raw pointers:

Foo foo;

Foo* ptrfoo = &foo;
ptrfoo->activate();

// "foo.isActive" returns true here

So why does that happen, and can I modify the object through a shared_ptr? If so, how can I do that?


Solution

  • Smart pointers are owning pointers. Because they own the memory they point to when you do

    std::shared_ptr<Foo> ptrfoo = std::make_shared<Foo>(foo);
    

    you don't get a pointer to foo but instead you get a pointer to an object that is a copy of foo. Anything you do to ptrfoo will not effect foo. This is one of the main differences between raw pointers and smart pointers. You can get a smart pointer to act like a raw pointer, but that is a lot of work and non owning raw pointers are okay so it's not really worth trying to modify smart pointers to get that behavior.