Total Articles 180
[Quiz]
Find a bug why run time error occurs.
[Source]
#include <iostream>
#include <string>
using namespace std;
#define SAFE_DELETE(A) { if(A != NULL) { delete (A); A = NULL; } }
class MyString
{
public:
string* m_str;
MyString() { m_str = NULL; }
MyString(const char* p) { m_str = new string(p); }
virtual ~MyString() { SAFE_DELETE(m_str); }
};
void write(MyString s)
{
if (s.m_str != NULL)
cout << *s.m_str << endl;
}
int main()
{
MyString s = "test";
write(s);
return 0;
}
[Download]
2011.09.14 13:42:14 (*.94.41.89)
복사생성자를 만들어주지 않아서 write 함수 진입시 복사된 m_str 이 중복 해제되는 현상이 발생하겠네요
그런데 최초 인스턴스 생성과 호출부분을 test 함수로 옮기신것으로 보아..
main 함수 종료시 메모리 중복해제 시도는 프로그램이 종료되는 시점이라 환경에 따라 문제가 안되는 경우도 있을수 있는건가요?
2011.09.17 15:56:59 (*.233.44.152)
얕은 복사 문제. 이 부분이 이해가 되지 않아서 투닥투닥 했던 기억이 나네요.
나중에 이해가 되긴 했지만 정말 마음에 안들어서 기분이 안좋았던 기억이 납니다.
개인적으로 왜 이와같은 개념을 만들었는지 도무지 이해가 되질 않습니다.
왜 변수부와 함수부를 나눠서 클래스를 만들 생각을 했을까요?
객체지향이라는 이념과 상충된다고 생각합니다.
2011.09.19 04:06:29 (*.4.203.182)
It has nothing to do with Object Oriented Programming.
This problem has a relationshtip to C++ language itself.
Youd' better learn"Nullary Constructor". http://en.wikipedia.org/wiki/Nullary_constructor
Change main code from
into
and you can figure out easily what kind of problem exists. :)