Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stl vector for classes with private copy constructor?

There is a class in our code, say class C. I want to create a vector of objects of class C. However, both the copy constructor and assignment operator are purposely declared to be private. I don't want to (and perhaps am not allowed) to change that.

Is there any other clean way to use/define vector<C> ?

like image 621
tanon Avatar asked May 11 '11 04:05

tanon


4 Answers

You could use a vector<C*> or vector<shared_ptr<C>> instead.

like image 110
Ernest Friedman-Hill Avatar answered Nov 18 '22 08:11

Ernest Friedman-Hill


No, it isn't, std::vector requires assignable concept. The authors of C must have had a good reason to prohibit this, you have to stick with whatever they provide to copy/assign instances of C. Either you use pointers as suggested above, or C provides other mechanism to copy/assign itself. In the latter case you could write an assignable proxy type for C.

like image 23
Paul Michalik Avatar answered Nov 18 '22 07:11

Paul Michalik


Do you have access to the boost library?

Create a vector of boost shared pointers.

   std::vector<boost:shared_ptr<C>>
like image 1
Andrew Shepherd Avatar answered Nov 18 '22 08:11

Andrew Shepherd


I have managed to do it by using just two friends:

template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
    friend class std::vector;
template<typename _T1, typename _T2>
    friend void std::_Construct(_T1* __p, const _T2& __value);

Put them inside your class declaration and voila!

I am using gcc 5.3.1.

like image 1
Tiago Cardoso Avatar answered Nov 18 '22 06:11

Tiago Cardoso