For such case:
class A
{
//implementation
};
class B
{
public:
B();
~B();
private:
std::vector<std::shared_ptr<A>> _innerArray;
};
what should I do in the B() to create an object with valid state? Do I need to manually call default constructor for every A object in array? And do I need to do something special in ~B()? If B class is example of bad design, feel free to say how to make it better. Thanks.
Edit
So, here is a scheme of what I really need here.

So real values stored only in array of A and all other objects are for storing connections.
The easiest example – A = dot, B = Line (or curve) going via selected dots and C = a plane described by lines. Hope it makes question more exact.
To create a
Bobject in a valid state you do not have to do anything more. You even do not have to declare and implement constructor and destructor forB.std::vector<std::shared_ptr<A>>that is a member ofBwill be default initialized inB‘s constructor which means it will not have any elements in a container yet. It will also be properly deleted in~Bthanks tostd::vectorandstd::shared_ptrdestructors.On the other hand if you for example want to initialize it somehow (i.e. 3 values) you can use
std::vector‘sstd::initializer_listconstructor in aB‘s constructor initialization list. For example:Remember that
std::make_shareduses perfect forwarding so you passA‘s constructor arguments as the function arguments and not the class object itself.Answering your concerns about the design I would like to encourage you to first think about the exclusive ownership of members in a vector before you decide to share them.
Above implementation is more effective on many grounds. First of all it makes your design more clear on who is responsible for the lifetime of
As. Nextstd::unique_ptris faster because it does not demand thread safe reference counting. And last but not least it does not cost any additional memory (compared to regular C pointer) whilestd::shared_ptrmay take tens of bytes (24-48) to store shared state data which is highly ineffective when you operate on small classes. That is why I always usestd::unique_ptras my first resort smart pointer and I only fallback tostd::shared_ptrwhen it is really needed.EDIT:
Answering your edit I would create 3 containers of classes
A,B,C. Depending of the fact if you need them to be polymorphic or not I would store either values like that (non-polymorphic types):or (polymorphic types):
in that order (
asmust live longer thanbsandbsmust live longer thancs). Then I would just havestd::vector<A*>insideBclass andstd::vector<B*>insideCclass without any smart pointers usage.I hope that helps.
EDIT:
Changed
std::vectortostd::dequein the first case which allows references/pointers to container elements survive containers extensions withpush_back(). However they will not survive erasing elements, sorting or other stuff.