次のコードは、非常に簡単な実行時エラーを発生させます。訂正しますか?
このコードは、リストを使用して STL ライブラリをテストするためのものです。
この問題は、Test::Test(const Test& t)と Test& Test::operator= (const Test& m)という 2 つの関数に起因しているように見えます。
エラーなしで実行したいだけです。
問題が発生する理由が正確にわかっている場合は、その理由を教えてください。
// ヘッダー
class Test
{
public:
int t;
char *name;
public:
Test() {
t = 1;
name = new char [strlen("test")+1];
strcpy(name, "ssss");
}
Test (int i) {
t = i;
}
Test(const Test& t);
~Test()
{
delete [] name;
}
Test& operator= (const Test& m);
char * get_name();
};
// 実装
Test::Test(const Test& t)
{
this->t = t.t;
this->name = new char[strlen(t.name)+1];
strcpy(this->name, t.name);
}
Test& Test::operator= (const Test& m)
{
if(this == &m) return *this;
if(this->name != NULL) delete[] name;
name = new char[strlen(m.name)+1];
strcpy(this->name, m.name);
this->t = m.t;
return *this;
}
char * Test::get_name()
{
return name;
}
// 主な機能
int main(int argc, const char * argv[])
{
Test a;
Test b(3);
Test c(4);
list <Test> t_list;
t_list.push_back(a);
t_list.push_back(b);
t_list.push_back(c);
list <Test>::iterator iter_begin = t_list.begin();
list <Test>::iterator iter_end = t_list.end();
for(; iter_begin != iter_end; iter_begin++)
{
printf("%d\n", iter_begin->t);
printf("%s\n", iter_begin->get_name());
}
list <Test> t_list2;
t_list2.push_back(c);
t_list2.push_back(b);
t_list2.push_back(a);
iter_begin = t_list2.begin();
iter_end = t_list2.end();
for(; iter_begin != iter_end; iter_begin++)
{
printf("%d\n", iter_begin->t);
printf("%s\n", iter_begin->get_name());
}
}