Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's all the fuss about C++ copy constructors? [duplicate]

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.

like image 990
bodacydo Avatar asked Jul 31 '10 14:07

bodacydo


People also ask

What is the point of a copy constructor?

A copy constructor is a member function of a class that initializes an object with an existing object of the same class. In other words, it creates an exact copy of an already existing object and stores it into a new object.

What is the purpose of copy constructor Why copy constructor argument should be constant in C ++?

Why copy constructor argument should be const in C++? When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified.

Does C have copy constructor?

When is the copy constructor called? In C++, a Copy Constructor may be called in the following cases: When an object of the class is returned by value. When an object of the class is passed (to a function) by value as an argument.


1 Answers

Copy constructors and assignment operators are very important in C++ because the language has "copy semantics", 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, but 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 maybe 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 copying 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 and 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&); // = delete in C++11
        Window& operator=(const Window&); // = delete in C++11
};

If the last part seems absurd (how can you make copies in the implementation by mistake) please note that in C++ it 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 likely 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 the 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, whoever will read your code will think that you simply forgot about them.

UPDATE

C++ is evolving and while most of what is said here is still valid now the language provides a better method to inform the compiler that copying and assignment shouldn't be allowed.

The new syntax (valid since C++11) is

struct Window {
    ...
    Window(const Window&) = delete;
    Window& operator=(const Window&) = delete;
};
like image 120
6502 Avatar answered Sep 17 '22 13:09

6502