C++で動的メモリ割り当てを行うクラスを定義した時は、代入演算子と copy constructor を定義しておく。これらが定義されていない場合、 このクラスを使うプログラム中で、これらを(暗黙的であっても)使うと default の copy constructor や代入演算子が使われるため、compile エラーとはならずに実行時に障害が発生する。実装例を示す。
class MyString
{
public:
MyString();
MyString(const MyString& from);
~MyString();
MyString& operator=(const MyString& from);
private:
size_t length;
char* buf;
};
MyString::MyString()
{
length = 0;
buf = NULL;
}
MyString::MyString(const MyString& from)
{
size_t i;
length = from.length;
buf = new char [length + 1];
for( i = 0; i < length; i++ )
buf[i] = from.buf[i];
buf[length] = 0;
}
MyString::~MyString()
{
delete [] buf;
}
MyString&
MyString::operator=(const MyString& from)
{
size_t i;
if( &from == this )
return *this;
delete [] buf;
length = from.length;
buf = new char [length + 1];
for( i = 0; i < length; i++ )
buf[i] = from.buf[i];
buf[length] = 0;
return *this;
}