CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

about copy constructor and copy assignment

Open sonicgemini opened this issue 4 years ago • 4 comments

there is a rule: "If you define a copy constructor, you must also define a copy assignment operator."

but copy constructor and copy assignment has different scenarios. In fact it is common that we need copy constructor, but we needn't copy assignment, and we cannot finish the code about copy assignment if the class has const or reference member. So for us, we just write copy ctor but without copy assignment, and we are not worried about the lack of defining operator= because, if any code use that, the compiler will notice us it cannot generate the operator= because & member cannot been generated.

So I think it is not a "must", right?

Thanks.

sonicgemini avatar Nov 05 '20 15:11 sonicgemini

Isn't it covered by the Exceptions paragraph of that guideline?

And you can always define it as deleted (= delete) if you don't want it to exist.

jwakely avatar Nov 05 '20 15:11 jwakely

I don't think it is covered as you describe. Which bit specifically? For convenience here is that excerpt

Exceptions: When any of the special functions are declared only to make them non-public or virtual, but without special semantics, it doesn't imply that the others are needed. In rare cases, classes that have members of strange types (such as reference members) are an exception because they have peculiar copy semantics. In a class holding a reference, you likely need to write the copy constructor and the assignment operator, but the default destructor already does the right thing. (Note that using a reference member is almost always wrong.)

I would go so far as to say that if you have a custom copy constructor and it doesn't make sense to have a copy assignment operator then you probably should =delete it as you describe. This ensures that it stays deleted even if the class is modified to remove/alter the members that prevent its definition.

However that would seem to be contradicted by

Prefer compiler-generated (including =default) special members; only these can be classified as "trivial", and at least one major standard library vendor heavily optimizes for classes having trivial special members. This is likely to become common practice.

shaneasd avatar Nov 05 '20 16:11 shaneasd

I was referring to this part:

In rare cases, classes that have members of strange types (such as reference members) are an exception because they have peculiar copy semantics.

jwakely avatar Nov 05 '20 16:11 jwakely

My reading of that is that it is specifically saying that reference members way require you to customize the copy constructor and assignment without needing to modify the destructor.

shaneasd avatar Nov 06 '20 04:11 shaneasd