Shared Pointers declaration

312 views Asked by At

I'm modifying my code to include shared pointers instead of raw pointers. Is the following declaration valid?

for(//some loop//){

std::shared_ptr<foo> tmp;
/..do stuff to tmp../
vectorofpointer.push_back(tmp);

Additionally, once tmp goes out of scope, will this affect my vector?

1

There are 1 answers

0
olovb On

Yes, it is ok.

See http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr:

1) Default constructor constructs a shared_ptr with no managed object, i.e. empty shared_ptr

See also http://en.cppreference.com/w/cpp/memory/shared_ptr:

A shared_ptr may also own no objects, in which case it is called empty […]

If your vector holds shared_ptr elements, your can still access the object pointed to after tmp has gone out of scope, since the reference count keeps the object alive.