GSI Forum
GSI Helmholtzzentrum für Schwerionenforschung

Home » CBM » CBMROOT » General » Effective C++
If you really want the copy constructor [message #13071 is a reply to message #13070] Fri, 17 February 2012 09:42 Go to previous message
Volker Friese is currently offline  Volker Friese
Messages: 365
Registered: April 2004
Location: GSI CBM
first-grade participant
From: *
The copy constructor which is created by default by the compiler if you do not do it yourself will just copy each data member by value. If your class just contains normal type members, this is usually want you want.

If your class, however, contains a pointer member, things are different, because the default copy constructor will not copy the object the pointer points to, but just the pointer value. So, the pointer member of the new object will point to the same location as that of the original object. If the original object is removed, then its destructor will delete the object its pointer member points to (if properly implemented). So, the pointer member of the new, copied object, will point to an invalid address. The best you can get is then a segmentation fault.

If for such a class you do not need the copy or assignment constructor, follow the instructions given in the mother posting. If you do need it, you have to implement it yourself. In most cases that means to manually copy the normal members one by one. In addition, for the pointer member you have to instantiate an object it points to, and use the copy constructor of this object to create it from the one of the original class.


class Example {

double firstMember;
FairMCPoint* pointerMember;

// Assignment operator
Example& operator = (Example const & source) {
firstMember = source.FirstMember;
pointerMember = new FairMCPoint(*(source.pointerMember));

// Copy constructor, using the assignment operator
Example(Example const & source) { *this = source; }


This is just an example, there is no general solution. You have to decide on your own what in your particular case the assignment operator and the copy constructor are supoosed to do.

Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Field maps available from the repository
Next Topic: Coordinate system for hit parameters
Goto Forum:

Current Time: Mon Apr 15 04:52:18 CEST 2024

Total time taken to generate the page: 0.00870 seconds