c++ - Pointer or local variable for the output parameter of a function -
if want use value of element in map output parameter of function, better declare smart pointer or locally?
for example:
// .h class { private: // below code preferred on // std::map<int, std::unique_ptr<b>>? std::map<int, b> map; public: void func1(); // message output parameter void func2(int, b* message); } // .cc void a:: func1() { b b; // better make b smart pointer , use std::move // transfer ownership map? map.insert(std::make_pair(1, b)); (const auto& x : map) { func2(x->first, &x->second); } }
in example above, better declare smart pointer b , pass pointer func2 instead?
thanks,
std::map
makes copies of put in it1, map
owns copy of b
provided func2
. there no need smart pointers here map
handle destruction of stored b
s.
in fact there no need pointers @ all. func2
void func2(int, b & message);
, use reference.
1 can store pointer in std::map
, , std::map
contain copy of pointer. data pointed @ not copied , needs external management handle destruction. case using smart pointer, storing pointers in container defeats many of benefits of using container in first place , best avoided.
Comments
Post a Comment