Reputation: 47
I am using a vector of shared pointers to custom objects as below:
std::vector<std::shared_ptr<Thing>> Things;
void Foo()
{
std::shared_ptr<Thing> newThing(std::make_shared<Thing>());
//do something with newThing
Things.push_back(newThing)
}
In some other function Bar
, I am trying to access the raw pointer from newThing as such with no issues:
void Bar()
{
Things.at(index).get();
}
But, since the scope of the shared pointer newThing
is lost after exiting foo()
, the destructor of the Thing
object should be called and the operation in Bar
should lead to a segfault. How am I still able to access this?
Upvotes: 0
Views: 241
Reputation: 16852
When Foo
exits newThing
gets deleted. At that point newThing
points to a Thing
and has ref count of 2 (the other reference is held by the vector Things
). When newThing
inside Foo
gets deleted it will decrement ref count to 1 and when you call Bar
it will access that existing object inside vector Things
.
Upvotes: 0
Reputation: 385264
since the scope of shared pointer
newThing
is lost after exitingfoo()
Yeah, but the element in Things
is a copy of that shared pointer.
The destructor of the
Thing
object should be called
No. The copied shared_ptr
inside the vector holds another "reference" to the original Thing
object, so the original Thing
object still exists too.
This is the whole point of shared_ptr
.
You really shouldn't use a thing without understanding what it is and what it does.
The operation in
Bar
should lead to a segfault.
No. Even if your code were wrong and you had undefined behaviour, you cannot guarantee a segmentation fault. You should get out of the habit of ever "expecting" a segmentation fault.
How am I still able to access this?
Because your code is fine, on both Windows and Android.
Upvotes: 3