Pergunta

Just a design/optimization question. When do you store pointers or objects and why? For example, I believe both of these work (barring compile 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 one difference comes when instantiating on stack or heap?

For example:

   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?
}

Also, sizeof(A) should be < sizeof(B)? Are there any other issues that I am missing? (Daniel reminded me about the inheritance issue in his related post in the comments)

So since stack allocation is faster than the heap allocation in general, but size is smaller for A than B, are these one of those tradeoffs that cannot be answered without testing performance in the case in question even with move semantics? Or some rules of thumbs When it is more advantageous to use one over the other? (San Jacinto corrected me about stack/heap allocation is faster, not stack/heap)

I would guess that more copy constructing would lead to the same performance issue, (3 copies would ~ 3x similar performance hit as initiating the first instance). But move constructing may be more advantageous to use the stack as much as possible???

Here is a related question, but not exactly the same. C++ STL: should I store entire objects, or pointers to objects?

Thanks!

Nenhuma solução correta

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top