oop - C++ prefered way to share objects between methods within the same class -
given class has 2 methods need share variable best way pass/share variable between them? assuming variable not needed anywhere else in class. if variable stl container, change anything?
i'm considering following 3 options:
instantiate variable in 1 method , return pointer, delete in other method.
class myclass { public: std::vector<int>* method1(); void method2(); }; std::vector<int>* myclass::method1() { std::vector<int> *my_int_vector = new std::vector<int>; //manipulate vector in way return my_int_vector; } void myclass::method2() { std::vector<int> *myvector; myvector = this->method1(); //manipulate vector in way delete myvector; }
this separates new , delete between methods seems to begging go wrong.
alternatively can use class private member property hold variable.
class myclass { private: std::vector<int> myvector; public: void method1(); void method2(); }; void myclass::method1() { //manipulate this->myvector } void myclass::method2() { this->method1(); //manipulate this->myvector }
this unnecessarily exposes variable rest of class.
finally, can create object in 1 method , pass reference.
class myclass { public: void method1(std::vector<int> *my_int_vector); void method2(); }; void myclass::method1(std::vector<int> *my_int_vector) { //manipulate my_int_vector in way } void myclass::method2() { std::vector<int> myvector; this->method1(&myvector); //manipulate myvector in way }
to me seems best solution not calling new or delete , variable not available whole class.
is assessment of alternatives correct , have missed other options better?
the preferred way make variable member if passing parameter 1 function other not possible.
so yes third option might best.
if variable stl container, change anything?
no. containers in c++ standard library normal objects too.
about second option:
this separates new , delete between methods seems to begging go wrong.
yes. using raw new
, delete
in first place begging trouble. don't allocate dynamically when don't have to. , when do, use smart pointers.
so in case pass vector value. or if function going called lot maybe make vector static
, return reference.
you mentioned second option it
unnecessarily exposes variable rest of class.
if really problem class might big and/or trying much. should consider splitting class smaller classes clear, minimal, well-defined responsibilities (srp).
which brings fourth option, might or might not make sense in case: store vector in own class, , make 2 methods members of class. store class member of myclass
.
Comments
Post a Comment