5

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.

enter image description 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.

9
  • 1
    Sanity check: do you need the pointer here at all? And if so, should it be a shared pointer? Nov 7, 2012 at 11:24
  • Class B is supposed to have access to but not own some objects stored somewhere else. I don't see using unique_ptr instead of shared_ptr making any sense here, but I am a noob to smart pointers. Nov 7, 2012 at 11:31
  • @Pavel You’re right: your scenario precludes the use of unique_ptr, and it mandates the use of pointers. However, if B isn’t supposed to take ownership I’d even consider using raw pointers instead of shared pointers. After all, the latter denote shared ownership (but maybe that’s what you require after all). Nov 7, 2012 at 11:35
  • @ПавелОганесян Do you intend for the lifetime of the pointed-at objects to be extended if they are contained in an instance of your class? If yes, then shared_ptr looks OK. Otherwise you could hold raw pointers. Nov 7, 2012 at 11:36
  • You should consider passing "somewhere else" as a parameter to the constructor of B and use the iterator version of std::vector constructor to initialize _innerArray, see my answer below. If B should not own the objects, weak pointers may be considered instead of shared pointers. I do not see a reason for using raw pointers.
    – JohnB
    Nov 7, 2012 at 11:39

5 Answers 5

5

To create a B object in a valid state you do not have to do anything more. You even do not have to declare and implement constructor and destructor for B. std::vector<std::shared_ptr<A>> that is a member of B will be default initialized in B's constructor which means it will not have any elements in a container yet. It will also be properly deleted in ~B thanks to std::vector and std::shared_ptr destructors.

On the other hand if you for example want to initialize it somehow (i.e. 3 values) you can use std::vector's std::initializer_list constructor in a B's constructor initialization list. For example:

class B
{
 public:
     B(): _innerArray{ std::make_shared<A>(),
                       std::make_shared<A>(),
                       std::make_shared<A>() } {}
    ~B() {}
 private:
     std::vector<std::shared_ptr<A>> _innerArray;
};

Remember that std::make_shared uses perfect forwarding so you pass A'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.

class B
{
 public:
     B();
    ~B();
 private:
     std::vector<std::unique_ptr<A>> _innerArray;
};

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. Next std::unique_ptr is 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) while std::shared_ptr may 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 use std::unique_ptr as my first resort smart pointer and I only fallback to std::shared_ptr when 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):

std::deque<A> as;
std::deque<B> bs;
std::deque<C> cs;

or (polymorphic types):

std::vector<std::unique_ptr<A>> as;
std::vector<std::unique_ptr<B>> bs;
std::vector<std::unique_ptr<C>> cs;

in that order (as must live longer than bs and bs must live longer than cs). Then I would just have std::vector<A*> inside B class and std::vector<B*> inside C class without any smart pointers usage.

I hope that helps.

EDIT:

Changed std::vector to std::deque in the first case which allows references/pointers to container elements survive containers extensions with push_back(). However they will not survive erasing elements, sorting or other stuff.

0
2

If you do it like that, the vector has a size of zero elements, i.e. the contents are trivially properly initialized. If the vector were of positive size (e.g. after calling resize on the vector), each of the elements would be properly initialized. Since the elements are shared_ptrs, the default constructor of shared_ptr would be called, which means that you would end up with a vector of empty pointers.

If you want to copy the contents from another container, use the iterator version of the vector constructor:

B (SomeContainerTypeContainingSharedPointers container)
: _innerArray (container.begin (), container.end () ) {
}

If you do not want to initialize the vector from a container, but from somewhere else (e.g. create the objects on the fly) -- write an input iterator type yourself (i.e. kind of a "factory iterator").

1

The vector is empty so you don't have to do anything special in the default constructor. And you don't need to do anything in B() either. The reference count of the shared_ptrs will be decreased automatically when the vector's destructor is called.

1

Bt default std::shared_ptr<A> will populate inner ptr with NULL. To create smart pointer use std::make_shared:

_innerArray.push_back(std::make_shared<A>(/*constructor params here*/));

But in your example vector is empty.

0

The default constructor already does everything needed. You can even leave B() out without any loss.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.