I'm just starting out with C++ and trying to get my head around smart pointers. Obviously, the following code will crash (I suppose it's because the assignment created a copy of the shared_ptr?). Is there a way to keep foo.Other
updated by calling some kind of set method on ptrs[3]
?
class Foo
{
public:
int X;
std::shared_ptr<Foo> Other;
Foo() : X(10) { }
};
int main()
{
Foo foo;
std::vector<std::shared_ptr<Foo>> ptrs(10);
foo.Other = ptrs[3];
std::shared_ptr<Foo> other = std::shared_ptr<Foo>(new Foo());
ptrs[3] = other;
std::cout << foo.Other->X << std::endl; // throws Access violation exception
return 0;
}
Edit: This is the exception I'm getting since it's pointing to null:
First-chance exception at 0x01219AEF in Test.exe: 0xC0000005: Access violation reading location 0x00000000. Unhandled exception at 0x01219AEF in Test.exe: 0xC0000005: Access violation reading location 0x00000000.