Reputation: 13637
For the first time, I'm using smart pointers in C++.
I've some question about std::shared_ptr
:
Set pointer by reference:
MyToy mytoy_1, mytoy_2;
set_mytoy(mytoy_1, some_data);
set_mytoy(mytoy_2, some_data);
shared_ptr<MyToy> ptr_mytoy(&mytoy_1);
Reset and new assignment:
ptr_mytoy.reset(&mytoy_2);
Reset without assignment:
ptr_mytoy.reset();
Set NULL
(?):
ptr_mytoy(nullptr);
Are these examples right?
How can I check if a smart pointer is "empty" (for instance, after .reset()
) or if is NULL
?
Upvotes: 1
Views: 7743
Reputation: 254531
Are these examples right?
The first two are wrong: they try to initialise and reset the shared_ptr
with an object, not a pointer.
UPDATE: the question has now been changed to initialise them from pointers to automatic variables. This is still wrong: the shared_ptr
will want to delete them, and it's an error to delete anything that wasn't created with new
.
Usually, the object will be created using new
, although it's better to use make_shared
to create it for you:
// Good
auto ptr = make_shared<MyToy>();
// Not so good, but sometimes necessary
MyToy * mytoy_2 = new MyToy;
ptr.reset(mytoy_2);
The third is correct. It release the object from the pointer, deleting it if there are no remaining pointers, and leaving the pointer empty.
The fourth is either dubious or wrong, depending on what null_ptr
is. If you mean nullptr
, then it's incorrect and shouldn't compile. If it's a null-valued pointer to MyToy
, then it leaves the shared_ptr
non-empty, but not owning anything either.
How can I check if a smart pointer is "empty" (for instance, after .reset())
if (ptr.use_count() == 0)
or if is NULL?
if (!ptr)
Upvotes: 5