Store pointers or objects in classes?

Just a design / optimization issue. When do you store pointers or objects and why? For example, I believe that both of these work (excluding compilation errors):

class A{
  std::unique_ptr<Object> object_ptr;
};

A::A():object_ptr(new Object()){}

class B{
  Object object;
};

B::B():object(Object()){}

I believe that one difference occurs when creating an instance on the stack or heap?

For instance:

   int main(){
      std::unique_ptr<A> a_ptr;
      std::unique_ptr<B> b_ptr;
      a_ptr = new A(); //(*object_ptr) on heap, (*a_ptr) on heap?
      b_ptr = new B(); //(*object_ptr) on heap, object on heap?

      A a;   //a on stack, (*object_ptr) on heap?
      B b;   //b on stack, object on stack?
}

In addition, there sizeof(A)should be < sizeof(B)? Are there any other problems that I am missing? (Daniel reminded me of the issue of inheritance in his related article in the comments)

, , , A, B, , ? ? ( / , /)

, (3 3 , ). .

, . ++ STL: ?

!

+5
4

A class, , .

, - (freestore), , A a .

, , . , A .

new, , , , , , new , .

, , .

+6

"", . , , , , . , , .

, . , ( ), ? - , , , dtor.

: , . .

edit: , : 1) ( ), 2) .

+5

, . , , . , , , , unique_ptr.

: , , ( "PIMPL" ). .

+5

, , . - :

template <class T>
struct tree_node { 
    struct tree_node *left, *right;
    T data;
}

, , node. ( , ), , .

, , ( ), , ( , ) . , " ", , , :

template <class T>
class some_string { 
    static const limit = 20;
    size_t allocated;
    size_t in_use;
    union { 
        T short_data[limit];
        T *long_data;
    };

    // ...

};

- . , , ( , ) swap , nothrow:

template <class T>
class parent { 
    T *data;

    void friend swap(parent &a, parent &b) throw() { 
         T *temp = a.data;
         a.data = b.data;
         b.data = temp;
    }
};

( ) :

... nothrow (.. : "swap " ). parent , , (, swap , T . ")

++ 11 (?) ( nothrow). , () - , .

, , , , , : , , , . () . , , , , . , , . , C, ++ ( ) - , , , , . (, Windows, Linux) ( , ).

, , , ( ), , ( , ) , . : , , / , "", .

, , , . :

  • (SBRM, aka RAII)
  • , "" .

: , , . - , , (?) , , . , , , , operator new .

+2

All Articles