c++ - Smart pointer: set by reference, reset, set null, null-check or reset-check -
for first time, i'm using smart pointers in c++. i've question std::shared_ptr
:
set pointer 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 , new assignment:
ptr_mytoy.reset(&mytoy_2);
reset without assignment:
ptr_mytoy.reset();
set
null
(?):ptr_mytoy(nullptr);
are these examples right?
how can check if smart pointer "empty" (for instance, after .reset()
) or if null
?
are these examples right?
the first 2 wrong: try initialise , reset shared_ptr
object, not pointer.
update: question has been changed initialise them pointers automatic variables. still wrong: shared_ptr
want delete them, , it's error delete wasn't created new
.
usually, object created using new
, although it's better use make_shared
create you:
// auto ptr = make_shared<mytoy>(); // not good, necessary mytoy * mytoy_2 = new mytoy; ptr.reset(mytoy_2);
the third correct. release object pointer, deleting if there no remaining pointers, , leaving pointer empty.
the fourth either dubious or wrong, depending on null_ptr
is. if mean nullptr
, it's incorrect , shouldn't compile. if it's null-valued pointer mytoy
, leaves shared_ptr
non-empty, not owning either.
how can check if smart pointer "empty" (for instance, after .reset())
if (ptr.use_count() == 0)
or if null?
if (!ptr)
Comments
Post a Comment