2

In my implementation, I have a vector of classes. Within each class there is a unique_ptr to a linked list. Only at runtime do I know the number of nodes that should be added to each of the linked lists. Some linked lists may have zero nodes. A simplified view of my class is:

class A
{
private:
    ...
    std::unique_ptr< std::list<MyListElement> > ptrList;
    ...

public:
    ...
};

Thanks to the unique_ptr, I had to jump through the hoops of first declaring a copy-constructor and copy-assignment-operator and setting them to = delete, and then providing definitions for a default-constructor, move-constructor and move-assignment-operator. After all this, I am now ready to call the function that initializes my linked lists for each object.

void A::initListElements(unsigned int numElements)
{
    if (numElements > 0)
    {
        std::unique_ptr< std::list<MyListElement> > tmp(new std::list<MyListElement>);
        ptrList = std::move(tmp);
    }
    else
    {
        ptrList = 0;
    }
}

Is this the correct way of doing it? Is there some way I can avoid creating the temporary unique_ptr 'tmp'?

Gautam
  • 1,079
  • 14
  • 21
  • 2
    "Thanks to the `unique_ptr`, I had to jump through the hoops"... is wanting to jump through the hoops the reason the code uses a `unique_ptr` at all? Because I see no other reason. – R. Martinho Fernandes Oct 21 '13 at 13:27
  • Why do you use a unique_ptr at all? `std::list` manages memory itself, no reason to allocate it on the heap. – lethal-guitar Oct 21 '13 at 13:30
  • Doesn't the compiler jump through all the hoops for you? – juanchopanza Oct 21 '13 at 13:31
  • My requirement was such that when an object of class A gets destroyed, then it should destroy it's linked list as well. So I thought having a unique_ptr to the list was the easiest way to get rid of it. – Gautam Oct 21 '13 at 13:34
  • A) you don't need a `unique_ptr` for this, just use an `std::list`. B) even with the unique pointer, the compiler should take care of the hoops you mention. – juanchopanza Oct 21 '13 at 13:35
  • 1
    @Gautam No need to do that - they are properly destructed whenever the containing object is. – lethal-guitar Oct 21 '13 at 13:35
  • 4
    You are missing the very basic concepts of C++. Get [a good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). If an object of class A has a `std::list` member, that member gets destroyed already when A objects are destroyed. It all comes for free, there's no need to find "easier" ways. – R. Martinho Fernandes Oct 21 '13 at 13:36

1 Answers1

4

You can avoid temporaries with reset method

ptrList.reset(new std::list<MyListElement>);

And you don't need else statement, I believe.

ixSci
  • 13,100
  • 5
  • 45
  • 79
  • With reset (and no else block), I was able to get it to work as expected, so I'm going to accept this answer. But it appears that I don't even need a unique_ptr for this particular problem! – Gautam Oct 21 '13 at 13:46