views:

277

answers:

5

Possible Duplicate:
When do we have to use copy constructors?

Why exactly are C++ copy constructors so important? I just learned about them and I don't quite see what is the fuss about them. It seems you should always write a copy constructor for your classes if you use pointers, but why?

Thanks, Boda Cydo.

+4  A: 

Simple: when C++ uses a default copy constructor, it copies the pointer, but not the data being pointed to. The result: two objects that point to the same data. If both think they own that data, and delete the pointer when their destructor is called, you've got a heap of trouble...

Owen S.
+1  A: 

Deep copy and Shallow copy

DumbCoder
+1  A: 

Every class in C++ has an implicit copy constructor that does a shallow copy of the object. Shallow means it copies the value of the members. So if there's a pointer the pointer value is copied so both object point to the same.

Most of the time this is not wanted, so you have to define your own copy constructor.

Often you don't even want to create copies of your object, so it's good style to declare a copy constructor, but not define it. (Empty declaration in header file).

Then, if you accidentially create a copy (e.g. returning an object, forgot the & when declaring a parameter-by-reference method etc.), you'll get a linker error.

If you declare the copy constructor private, you'll also get a compiler error (if used outside the class).

To summarize it: It's always good style to declare the copy constructor explicitly - especially if you don't need on at all: Just write

private:
  MyClass(const MyClass&);

in your class definition to disable the copy constructor of your class.

IanH
+7  A: 

Copy constructor and assignment operators are very important in C++ because the language has "copy semantic", that is to say when you pass a parameter or store a value in a container a copy of the object is passed or stored. How can C++ make a copy or perform an assignment on an object ? For native types it knows by itself, for user defined types instead it automatically generates a member-by-member copy construction or assignment.

More explicitly if you declare for example:

class P2d
{
    public:
        double x, y;
        P2d(double x, double y) : x(x), y(y)
        { }
};

the C++ compiler automatically completes your code to

class P2d
{
    public:
        double x, y;
        P2d(double x, double y) : x(x), y(y)
        { }

        P2d(const P2d& other) : x(other.x), y(other.y)
        { }

        P2d& operator=(const P2d& other)
        {
            x = other.x;
            y = other.y;
            return *this;
        }
};

Are these automatically generated copy constructor and assignment operators correct for your class? In many cases yes... but of course may be those implementations are totally wrong. Quite often for example when you have pointers contained inside your objects then just copying the pointer when you want to make a copy of the object is not the right thing to do.

You must understand that C++ does a lot of copies of objects, and you must understand what type of copy it will do for classes you defined. If the automatically generated copy is not what you need then you must either provide your own implementation, or you must tell the compiler that copy should be forbidden for your class.

You can prevent the compiler from making copies by declaring a private copy constructor and assignment operator, and by not providing an implementation. Because those are private functions any external code that is going to use them will get a compiler error, and because you declared them but you didn't implement them you will get a link error if by mistake you end up making copies inside the class implementation.

For example:

class Window
{
    public:
        WindowType t;
        Window *parent,
               *prev_in_parent, *next_in_parent,
               *first_children, *last_children;
        Window(Window *parent, WindowType t);
        ~Window();

    private:
        // TABOO! - declared but not implemented
        Window(const Window&);
        Window& operator=(const Window&);
};

If the last part seems absurd (how can you make copies in the implementation by mistake) please note that in C++ is very very easy to make extra copies by mistake because the language has been built around the concept of copying things around.

A golden rule is that if your class has a destructor (because it needs to do some cleanup) then most probably a member-by-member copy is not the right thing to do... and also if you have special logic to do a copy construction then a similar logic is probably needed also in assignment (and vice versa). So the rule, known as Big Three, states that either your class has no custom destructor, no copy constructor, no assignment operator or your class should have all three of them.

This rule is so important that for example if for any special case you end up with a class that just needs a destructor (I can't think a sensible case... but let's just say you found one) then please remember to add as a comment that you thought about it and you know that the implicitly generated copy constructor and assignment operators are ok. If you don't add a note about the other two, who will read the code will think that you simply forgot about them.

6502
anon
I think I got this from effective C++ but I'm not sure and I can't find the CD or the nice HTML file any more, most probably you're right. C++ FAQs (Cline) talks about the Big Three but for some reason Three Amigos got stuck better in my mind and I think it's more colorful (see http://movies.yahoo.com/movie/1800127037/info) and fits better.Also please don't tell anyone... but by the way I'm not a fan of UML, in my opinion such a nice name is sort of wasted for that ;-)
6502
Great explanation. Thank you!
bodacydo
+2  A: 

Why exactly are C++ copy constructors so important?

Copy constructors aren't needed in most other languages because they either:

  • Don't have pointers (e.g., old versions of BASIC), in which case copying objects is always safe, or
  • Have nothing but pointers/references (e.g., Java, Python), in which case copying is rare, and then can be done with a copy() or clone() method.

C++ prefers value semantics but also uses a lot of pointers, which means that:

  • Objects get copied a lot, and
  • You have to specify whether you want a shallow or deep copy, for reasons the others have mentioned.
dan04