Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smart pointers vs. value as member variables

I have a class A which has member variables of types M and N. The lifetimes of those objects are supposed to be limited by the lifetime of A.

I'm considering

class A {
    M member1;
    N member2;
}

vs.

class A {
    std::unique_ptr<M> member1;
    std::unique_ptr<N> member2;
}

I'm not entirely sure which is better, since they both accomplish what I want. The lifetime of the members are bound to the object, and I don't need to manually manage memory. What are the advantages and disadvantages of each setup?

like image 540
user6664740 Avatar asked Aug 01 '16 19:08

user6664740


2 Answers

use std::unique_ptr if

  1. M and N are base classes of polymorphic hierarchies
  2. member1 and member2 are optional members which can be nullptr
  3. M and N are large enough which cannot be allocated on program stack
like image 154
AnatolyS Avatar answered Oct 19 '22 01:10

AnatolyS


Yep, both are correct, but...

In general, there's an extra cost to dynamically allocating the objects vs keeping them as just simple members. You'd have to pay the edtra overhead of allocating theor memory from the free store, as opposed to simply using memroy allocated for the A of which they are part. You'd also have an indirect ref whenever you needed to access them.

You still might want to go the smart pointer route if the cost buys you something. For example :

  1. You might want to change the values of member1 or member2 throughout the lifetime of an A object. The smart pointer method could make that a cheap operation if M and N objects are large.
  2. You might want take advantage of polymorphism. If M or N was a base class, the pointer-based implementation would have the flexibility to use subclasses of M or N.
  3. The pointer based implementation could allow you to delay allocating the member1 or member2 until a later, more appropriate, time in the lifecycle of the A.
like image 20
D Hydar Avatar answered Oct 19 '22 01:10

D Hydar