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

5

5

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> ?

Casseycassi answered 11/5, 2011 at 4:4 Comment(0)
L
9

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

Lenticel answered 11/5, 2011 at 4:6 Comment(0)
H
2

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.

Hypnotherapy answered 11/5, 2011 at 7:25 Comment(0)
G
1

Do you have access to the boost library?

Create a vector of boost shared pointers.

   std::vector<boost:shared_ptr<C>>
Gizela answered 11/5, 2011 at 4:7 Comment(0)
S
1

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.

Schizophrenia answered 6/7, 2016 at 0:58 Comment(0)
U
1

You may use move constructor here.

#include<iostream>
#include<vector>

class Road
{
   Road(const Road& obj){}                            //copy constructor
   Road& operator=(const Road& obj){ return *this; }  //copy assignment

   public:
   /*May use below commented code as well
     Road(const Road&)=delete;
     Road& operator=(const Road&)=delete;
   */

   Road()=default;                                    //default constructor
   Road(Road&& obj){}                                 //move constructor
   void display(){ std::cout<<"Object from myvec!\n"; }
};

int main()
{
   std::vector<Road> myVec;
   Road obj;
   myVec.push_back(std::move(obj));

   myVec[0].display();
   return 0;
}
Unalloyed answered 17/8, 2019 at 4:15 Comment(3)
You have wrong move constructor semantics. It is nonsense to move from const object.Tunisia
Thank You @DmitryKuzminov for pointing out. I mean to achieve the goal using move constructor as well. I have removed const from move constructor.Unalloyed
One more concern: move constructor shouldn't throw exceptions (should be noexcept). Otherwise vector cannot guarantee the consistency when reallocating the buffer, and can prefer copy constructor instead.Tunisia

© 2022 - 2024 — McMap. All rights reserved.