c++ - Should I use smart pointers in this situation? -
i know go-to rule use shared_ptr
s or other smart pointers. however, i'm not sure how implement without copy ctor'ing std::make_shared
. i'll elaborate:
the problem
i want create tree-like expression, like:
struct foo{ std::vector<foo*> v; };
this allows me following:
foo add(foo& f1, foo& f2){ return foo {&f1, &f2}; }
that's good, because 2 become children of new node.
i want following evaluated correctly:
foo x, y; auto z = add(x,y); assert(z.v[0] == &x && z.v[1] == &y);
this way, there's no copying , it's good. however, have resource management issue here.
addressing resource management issue
if these elements allocated on heap, , unknowingly might, we'll run memory leak. best way use smart pointers raii:
struct foo{ std::vector<std::shared_ptr<foo> > v; }; foo add(foo& f1, foo& f2){ return foo {std::make_shared<foo>(f1), std::make_shared<foo>(f2)}; }
this good, we're calling copy ctor of f1 , f2 here. suppose copying takes long time , don't want incur cost.
we definitely, cannot do:
foo add(foo& f1, foo& f2){ return foo {std::shared_ptr<foo>(&f1), std::shared_ptr<foo>(&f2)}; }
because whenever remove z
in z = x+y
, call delete
on each of x
, y
, allocated on stack. and not want delete
things on stack.
so should in case?
let me know if should supply more information on context.
accept smart pointer. applying notion of smart pointers correctly means have think ownership semantics of data, , not calling new/delete automatically.
you accept reference non-const object. not imply sharing, modification of objects. , correctly noted, creating smart pointers them spells disaster.
the caller of add
(even if it's you) must know data pass shared. , way them know if pass smart pointer themselves. should change add
this:
foo add(std::shared_ptr<foo> f1, std::shared_ptr<foo> f2){ return foo{f1, f2}; }
now, way user of add
can blow intentionally. won't. furthermore, said user has more flexibility in calling code. can control allocator , deleter each object pass.
wiki
Comments
Post a Comment