c++ - allocate objects on the stack (with copies) or heap (with pointers) -


i have basic questions using stack vs heap. there's bunch of answers out there, i'm not sure how relate following.

i think it's easier explain way of example...

is "better" do

struct widget3 {     widget3(std::shared_ptr<widget1> widget1, std::shared_ptr<widget2> widget2)     : _widget1(std::move(widget1))     , _widget2(std::move(widget2))     {     }      void dosomething()     {         std::cout << _widget1.hello() << _widget2.hello();     } private:     std::shared_ptr<widget1> _widget1;     std::shared_ptr<widget2> _widget2; }; 

or this

struct widget3 {     widget3(const widget1 & widget1, const widget2 & widget2)     : _widget1(widget1)     , _widget2(widget2)     {     }      void dosomething()     {         std::cout << _widget1->hello() << _widget2->hello();     } private:     widget1 _widget1;     widget2 _widget2; }; 

the second example causes copy widget1 , widget2, lets create these objects once @ beginning of program , don't care cost (performance , memory) of copying objects.

is somehow faster use second example, _widget1 , _widget2 on stack?

your second way better because there no chance of memory leaks, in case chose not use smart pointer.

there no guarantee done on stack, though.

what if wrote:

widget1 widget1; widget2 widget2; widget3 *widget3 = new widget3(widget1, widget2);  int main(){     // 'widget3'     delete widget3; } 

what then?

you should prefer not using pointers whenever possible, it's safer. if there multiple handles data , can't pass reference (for whatever crazy reason) means, go example 1.

it's method better in situation. no method always better another.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -