简体   繁体   中英

Overloaded copy constructor

I encountered some code where one guy has overloaded copy constructor and assignment operator, like this:

 Prod(const Prod& src) {  
        _id    = src._id;
        _name  = src._name;
        _group = src._group;
        ...
}

 Prod& operator=(const Prod& src) {  
        _id    = src._id;
        _name  = src._name;
        _group = src._group;
        ...
}

The thing I find strange is that none of the member variables in the Prod class are pointers. So why is there a need to overload the copy constructor and = operator as above?

If the class doesn't manage resources, then you're right, there's no need to overload them. If it's used as a base class and it has a virtual destructor, they're probably there to obey the rule of three, although the C++11 alternative = default would be cleaner than actually implementing them.

On a side-note, the copy constructor can be implemented using operator = to avoid duplicating the logic:

Prod(const Prod& src) {  
   *this = src;
}

There was a rule of three and then there's now sa rule of five which are very likely to be superseded in a rule of zero .

Maybe someone wasn't sure wand just added some extra code.. ;)

In general, when all of the member fields are simple or automatically managed (that is, with proper ctors, copyctors, movectors, assignement, dtors etc), then there's no point in writing anything. See the rule-of-zero. However, this may a part of a code that was created under older version of the standard or at some compiler that was, well, hairy, and it might have been required at some point of time in the past. Now probably you may delete it and leave to default implementations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM