Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a container of noncopyable elements

Is there a way use STL containters with non-copyable elements?

something like this:

class noncopyable
{
    noncopyable(noncopyable&);
    const noncopyable& operator=(noncopyable&);
public:
    noncopyable(){};
};

int main()
{
    list<noncopyable> MyList; //error C2248: 'noncopyable::noncopyable' : cannot access private member declared in class 'noncopyable'
}
like image 367
Vargas Avatar asked Sep 17 '09 17:09

Vargas


3 Answers

No, non-copyable elements can't be in C++ container classes.

According to the standard, 23.1 paragraph 3, "The type of objects stored in these components must met the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types."

like image 120
David Thornley Avatar answered Nov 04 '22 20:11

David Thornley


One option is to create a list of pointers to the elements (preferrably a shared_ptr). This is not exactly what you want but it will get the job done.

like image 28
JaredPar Avatar answered Nov 04 '22 22:11

JaredPar


Another option is to use the Boost Pointer Container library. This acts much like a standard container of std::auto_ptrs would, were such a thing possible: it retains exclusive ownership of its elements, and it cannot be copied. It also has less overhead than a standard container of shared_ptrs.

like image 25
Alice Purcell Avatar answered Nov 04 '22 21:11

Alice Purcell