The standard example is a class that manages a resource:
struct Foo
{
Bar * p;
Foo() : p(new Bar) { }
~Foo() { delete p; }
// copy, assign
};
An object of type Foo
has a value, but that value is not copyable by copying the object representation (which is just the value of p
in this case). Copying an object of type Foo
requires copying the semantics of the class, which say "an object owns the pointee". A suitable copy thus requires an appropriate, user-defined copy constructor:
Foo::Foo(Foo const & rhs) : p(new Bar(*rhs.p)) { }
Now the object representation of an object of type Foo
is different from the object representation of a copy of such an object, although they have the same value.
By contrast, the value of an int
is the same as that of another int
as soon as the object representations coincide. (This is a sufficient, though not necessary, condition, due to padding.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…