开发者

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

开发者 https://www.devze.com 2023-01-09 22:10 出处:网络
This question already has answers here: Closed 12 years ago. 开发者_如何学Go Possible Duplicate: When do we have to use copy constructors?
This question already has answers here: Closed 12 years ago. 开发者_如何学Go

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.


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;
};


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...


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.


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.


Deep copy and Shallow copy

0

精彩评论

暂无评论...
验证码 换一张
取 消