Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm wondering why MemberwiseClone is defined as protected. This means that only derived types can access it. What is the problem if it was defined as public?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
990 views
Welcome To Ask or Share your Answers For Others

1 Answer

Pavel Minaev's answer from another discussion:

Others have already explained about MemberwiseClone, but no-one gave the explanation of why it is protected. I'll try to give the rationale.

The problem here is that MemberwiseClone just blindly copies the state. In many cases, this is undesirable. For example, the object might have a private field which is a reference to a List. A shallow copy, such as what MemberwiseClone does, would result in new object pointing to the same list - and the class may well be written not expecting the list to be shared with anyone else.

Or an object can have some sort of ID field, generated in constructor - again, when you clone that, you get two objects with the same ID, which may lead to all kinds of weird failures in methods assuming that ID is unique.

Or say you have an object that opens a socket or a file stream, and stores a reference to that. MemberwiseClone will just copy the reference - and you can imagine that two objects trying to interleave calls to the same stream isn't going to end well.

In short, "cloning" is not a well-defined operation for arbitrary objects. The fact that memberwise operator= is provided for all classes by default in C++ is more of a nuisance, as all too often people forget that it's there, and do not disable it for classes for which copying doesn't make sense, or is dangerous (and there are surprisingly many such classes).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...