infoclogged
infoclogged

Reputation: 3997

Do I have to write explicitly a copy constructor to copy a vector of objects into another

I have a vector of user defined objects such as

std::vector<UserDefinedClass> list_of_objects;

The UserDefinedClass doesnt have any explicit copy constructor.

Now I would like to make a copy of them. So, I define

std::vector<UserDefinedClass> list_of_objects_copied;
list_of_objects_copied = list_of_objects;

Do I really need a copy constructor to iterate the vector and copy the objects in the vector one by one?

The error is

error: use of deleted function ‘UserDefinedClass& UserDefinedClass::operator=(const UserDefinedClass&)’

If I use a built in object such as int, double etc, I dont have any problem in copying the list.

Class definition

UserDefinedClass {
private:
    int &m_a;
public:
    UserDefinedClass(int a):m_a(a) {};
};

Upvotes: 1

Views: 349

Answers (3)

Alan Birtles
Alan Birtles

Reputation: 36379

Yes if you want to copy your objects by copying them into another vector you need a copy constructor. If you want to avoid the copy you can either move the first vector into the second which would invalidate the first vector or store pointers in your vector (ideally a shared_ptr) which can then be copied without copying the underlying objects.

To make your class copyable change the reference member to a pointer:

UserDefinedClass {
private:
    int *m_a;
public:
    UserDefinedClass(int& a):m_a(&a) {};
};

You can still keep the parameter passed to the constructor a reference to guarantee that the value is not null.

Upvotes: 0

super
super

Reputation: 12928

A reference has to be initialized. When you do this you are trying to assign to the reference after it's been created.

What would work is to construct a copy from the other vector.

std::vector<UserDefinedClass> list_of_objects = { ... };
std::vector<UserDefinedClass> list_of_objects_copied{list_of_objects};

Upvotes: 0

Mark B
Mark B

Reputation: 96233

Your UserDefinedClass has a reference member variable. Reference members can't be rebound after construction, so the class is not copy-assignable by default, which means a vector of them also can't be copy-assigned.

You can copy-construct to create a new copy of the items, or depending on your needs you could create your own copy-assignment operator that does something different with the reference member.

Upvotes: 4

Related Questions