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?
use std::unique_ptr if
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 :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With