メンバーが POD 型であるか、それ自体がコピー可能である場合、コンパイラは既定のコピー コンストラクターを生成します。
class Foo
{
public:
Foo(int x, int y, int z, const std::string& name)
: x_(x), y_(y), z_(z), name_(name)
{
}
private:
int x_, y_, z_;
std::string name_;
};
この例のクラスは、デフォルトのコピー コンストラクターを使用してコピーできます。以下はすべて正しいです。
Foo a(1, 2, 3, "four");
// copy construct b from a, using the compiler provided default copy constructor
Foo b(a);
Foo c(5, 6, 7, "eight");
// copy c from b, c's current values are "lost"
c = b;
浅いコピーで期待どおりに動作しないユーザー定義型を含むクラスがある場合は、独自のコピー コンストラクター、代入演算子、およびデストラクターを記述する必要があります。これが、ほとんどの経験豊富な C++ 開発者が、可能な限り生のポインター (および他の同様の概念) を避ける理由です。
class BadFoo
{
public:
BadFoo() : x_(new int(5))
{
}
// ... You need to manage the memory of x_ on your own
// This means following the rule of 3 (C++03) or 5 (C++11)
private:
int* x_;
};
参照: 3 のルール