Shared_ptr not changing object (Visual studio 2012)

I have a really strange problem. I cannot change the object I am pointing to using shared_ptr.

Sample code:

#include<memory>
#include<iostream>
using namespace std;

class foo
{
public:
    int asd;
    foo(){}
    ~foo(){}
};


 void d(shared_ptr<foo> c)
{
    c->asd = 3;
}

void main()
{
    foo a;
    a.asd = 5;
    d(make_shared<foo>(a));
    cout<<a.asd; //asd is still 5
}

      

As far as I know, you can access the object pointed to by shared_ptr using the "->" operator, so what am I doing wrong here? How can I change an asd variable inside a class using a shared pointer?

+3


source to share


2 answers


// create a temporary object by copying a
// the shared pointer you pass to d function actually points to this temporary object
d(make_shared<foo>(a));

// allocate and store foo object in shared_ptr instead
auto p_a(make_shared<foo>());
p_a->asd = 3;
d(p_a);

      



+1


source


... so what am I doing wrong here?

From cppreference tostd::make_shared

[ highlight ):



template< class T, class... Args >
shared_ptr<T> make_shared( Args&&... args );

      

Creates an object of type T

and wraps it in std::shared_ptr

, using it args

as a parameter list for the constructorT

.

In your case, you provide an instance foo

as an argument std::make_shared

to be used when constructing a new object of the type foo

; that is, using the default copy of CTOR foo

( foo(const foo&)

). This new object will be temporary and call-only d(...)

.

0


source







All Articles