unique_ptr 사용시 클래스의 소멸자는 필요가 없을까요?

dltkddyd의 이미지

아래에 Resouce라는 클래스가 있습니다. 그리고 다음과 같이 unique_ptr로 내부 포인터가 Resouce 객체를 가리키도록 했습니다.

unique_ptr > unique7(80,"Robert Jim"));

에서 내부포인터가 가리키는 객체는 Resource라는 객체인데, unique_ptr로 생성된 Resource라는 객체는 ~Resouce라는 소멸자가 필요없나요?
C++ 표준 라이브러리(니콜라이 조슈티스 저, 한정애 역) p147의 6행에 따르면 "unique_ptr을 사용하면 객체가 삭제될 때 멤버도 같이 삭제되기 때문에 소멸자를 가질 필요가 없다"라고 합니다. 그런데 이것이 정말 사실인지 궁금합니다. 그렇다라고 한다면 unique_ptr에서

delete[] name;

이라는 것으로 메모리를 삭제한다는 것인지? 아니면 이것도 역시 운영체제에서 알아서 메모리를 회수한다는 것인지? 어떤 식으로 name이라는 메모리가 회수되는 것인가요? 소멸자는 호출이 안되나요?
문제의 코드는 다음과 같습니다.

template<typename targ>
class Deleter {
public:
	void operator()(targ* p) {
		cout<<"Deleting...."<<endl;
		delete p;
	}
};
template<typename targ>
class Deleter<targ[]> {
public:
	void operator()(targ* p) {
		cout<<"Deleting DArr...."<<endl;
		delete[] p;
	}
};
 
class Resource {
public:
	int score;
	char* name;
	Resource() {
		score=0;
		name=NULL;
	}
	Resource(int _score, const char* _name) {
		score=_score;
		name=new char[strlen(_name)+1];
		strcpy(this->name,_name);
		//name[strlen(_name)]=0;
	}
	~Resource() {
		score=0;
		delete[] name;
	}
};
 
class Resource {
public:
	int score;
	char* name;
	Resource() {
		score=0;
		name=NULL;
	}
	Resource(int _score, const char* _name) {
		score=_score;
		name=new char[strlen(_name)+1];
		strcpy(this->name,_name);
		//name[strlen(_name)]=0;
	}
	~Resource() {
		score=0;
		delete[] name;
	}
};
 
int main() {
	unique_ptr<Resource,Deleter<Resource> > unique7(new Resource(80,"Robert Jim"));
	return 0;
}
mirheekl의 이미지

원문이 혹시 이것인가요?
unique_ptrs as Members

By using unique_ptrs within a class, you can also avoid resource leaks. If you use a unique_ptr instead of an ordinary pointer, you no longer need a destructor because the object gets deleted with the deletion of the member.

이게 맞다면, "unique_ptr을 사용하면 객체가 삭제될 때 멤버도 같이 삭제되기 때문에 소멸자를 가질 필요가 없다"는건 그 unique_ptr이 참조하는 객체들의 소멸자들이 모두 정상적으로 선언되어있고 unique_ptr이외에 다른 로컬 리소스가 해당 클래스내에 없을 경우입니다. 즉 가령 ClassA 클래스의 멤버로 unique_ptr(ClassB)라는게 있다면 ClassB의 소멸자 호출이 보장된다는 뜻일 뿐입니다. unique_ptr()로 관리되지 않는 멤버가 있다면, 당연히 소멸자를 통해 해제해주셔야 합니다.

저 번역문은 이렇게 받아들여야 되겠네요. "unique_ptr을 일반 포인터대신에 (클래스 내에서) 사용하면, 그 멤버가 delete될때 해당 객체도 같이 delete되므로 (해당 멤버를 삭제하기 위한) 소멸자는 필요가 없다" 결국 말씀드린대로 unique_ptr이 해당 클래스 자체를 어떻게 자동으로 관리해주는게 아니고 자기가 레퍼런스하는 놈의 소멸자 호출만 보장하는 겁니다.

본문의 소스에선 unique_ptr로 선언된 멤버가 없으므로 아무런 관계가 없는 내용이겠네요.

--

dltkddyd의 이미지

'C++ 표준라이브러리'라는 참고서적의 뜻은 그 뜻이 아니었네요. 뒤에 언급된 내용을 못 봐서 이해를 제대로 못했던 것이었네요. 그러니까 클래스 내부에서 unique_ptr을 선언했을 때 그 내부포인터에 대해 delete를 해서 그 동적메모리를 해제할 필요가 없다는 것이었네요. 다음에는 책의 내용을 충분히 살펴보고 글을 올려야겠습니다. 죄송...

본인 맞습니다.
인증샷
우헤헤헤... 로 대신합니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.