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?
source to share
... 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 instd::shared_ptr
, using itargs
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(...)
.
source to share