C.61: A copy operation should copy
C.61: copies of the copy operation should have the effect of
Reason (reason)
That is the generally assumed semantics. After x = y, we should have x == y. After a copy x and y can be independent objects (value semantics, the way non-pointer built-in types and the standard-library types work) or refer to a shared object (pointer semantics, the way pointers work).
This is a convention of semantics. When x = y is executed, we should also be considered x == y. After the copy operation, x and y may be two separate objects (value semantics, such as built-in types and non-pointer type as standard library), or with a different shared object reference (pointer semantics, as the behavior that the pointer).
Example (Example)
class X { // OK: value semantics
public:
X();
X(const X&); // copy X
void modify(); // change the value of X
// ...
~X() { delete[] p; }
private:
T* p;
int sz;
};
bool operator==(const X& a, const X& b)
{
return a.sz == b.sz && equal(a.p, a.p + a.sz, b.p, b.p + b.sz);
}
X::X(const X& a)
:p{new T[a.sz]}, sz{a.sz}
{
copy(a.p, a.p + sz, p);
}
X x;
X y = x;
if (x != y) throw Bad{};
x.modify();
if (x == y) throw Bad{}; // assume value semantics
Example (Example)
class X2 { // OK: pointer semantics
public:
X2();
X2(const X2&) = default; // shallow copy
~X2() = default;
void modify(); // change the pointed-to value
// ...
private:
T* p;
int sz;
};
bool operator==(const X2& a, const X2& b)
{
return a.sz == b.sz && a.p == b.p;
}
X2 x;
X2 y = x;
if (x != y) throw Bad{};
x.modify();
if (x != y) throw Bad{}; // assume pointer semantics
Note (Note)
Prefer value semantics unless you are building a "smart pointer". Value semantics is the simplest to reason about and what the standard-library facilities expect.
Unless you are building some kind of "smart pointer", otherwise better value semantics. Value semantics but also the most easily understood standard library functions expect.
Enforcement (Suggestions)
(Not enforceable) No
Description link
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c61-a-copy-operation-should-copy
I think this article helpful? Welcome thumbs up and share it with more people.
Read more updated articles, please pay attention to micro-channel public number of object-oriented thinking []