Copy constructor for object with vector fo object

2019-06-11 00:08发布

I have a class A with a vector<Object> object_list_ as a member variable.

I know that if I had a vector of pointers I would have needed to write a specific copy constructor to achieve a deep copy. However, in this case, as I don't have pointers, when copying an object of type A, the default copy constructor will automatically also call the copy constructors of Object or each element in object_list_ or do I have to write my own copy constructor to do that?

2条回答
The star\"
2楼-- · 2019-06-11 00:17

The default copy constructor for your class will call the default copy constructor for each member, in the order they're declared in the class. One rule of thumb is that if you don't need a special destructor, then you don't need to change the copy constructor, copy assignment, move constructor, or move assignment either. (Though deleting them may still make sense, depending on the class).

A vector's copy constructor will make a copy of its elements, using their copy constructors. If those are pointers, it will copy the pointers, which means they'll point at the same data as the origonal vector. 99% of the time this is what you want. Though very rarely you may want to replace your class' copy constructor to make the vector do something else.

It sounds like you don't need to make a copy constructor in your case.

查看更多
我想做一个坏孩纸
3楼-- · 2019-06-11 00:19

Copy constructors of member variables are called all the way down. So if a default one was generated (and it would be in this case) then it gets called.

查看更多
登录 后发表回答