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!
If you have a big object inside your
Aclass, then I’d store a pointer to it, but for small objects, or primitive types, you should not really need to store pointers, in most cases.Also, when something is stored on the stack or on the heap (freestore) is really implementation dependent, and
A ais not always guarantueed to be on the stack.It’s better to call this an automatic object, because it’s storage duration is determined by the scope of the function it is declared in. When the function returns,
awill be destroyed.Pointers require the use of
newand it does carry some overhead, but on machines today, I’d say it is trivial in most cases, unless of course you have startnewing up millions of objects, then you will start seeing the performance issues.Each situation is different, and when you should and shouldn’t use a pointer, instead of an automatic object, is largely dependent on your situation.