auto_ptr 쓰세요?

girneter의 이미지

auto_ptr 이 뭔지는 알겠고
언제 써야 하는지도 알겠는데,
실제로 쓰는 경우가 있나요?

객체를 new 로 heap 에 만들지 말고
그냥 stack 에 만들면
auto_ptr 을 쓰지 않아도
함수가 끝나면 저절로 해제되자나요

책을 봐도 그렇게만 설명이 되어 있구요.

혹시 객체를 stack 에 만드는것보다 더 나은
요긴하게 쓸만한 경우가 있습니까?

죠커의 이미지

동적할당하지 않고 가상함수를 이용할 방법이 있나요? :-)

cinsk의 이미지

CN wrote:
동적할당하지 않고 가상함수를 이용할 방법이 있나요? :-)

Virtual function의 사용과 dynamic memory allocation과는 별개로 알고 있습니다:

#include <iostream>

struct base {
  virtual void foo() { std::cout << "base::foo" << std::endl; }
};

struct derived : public base {
  void foo() { std::cout << "derived::foo" << std::endl; }
};

int
main()
{
  derived d;
  base *b = &d;
  b->foo();
  return 0;
}
doldori의 이미지

auto_ptr은 알고 계신 기능만으로도 쓸모가 있습니다. 그것 말고도 중요한 점이
또 있는데 예외에 안전하다는 것입니다.

struct S
{
    ~S() { cout << "~S()\n"; }
};

void i_will_throw() { throw 0; }

void f()
{
    auto_ptr<S> ap(new S);
    i_will_throw();
}

f()에서 예외가 발생하면 S의 소멸자가 호출되는 것을 확인할 수 있을 것입니다.
plain pointer로는 불가능한 일이죠.

ps. 실은 저는 auto_ptr보다는 boost::shared_ptr을 많이 씁니다. (auto_ptr은
STL의 컨테이너에는 사용될 수 없다는 점이 너무 불편해서요.)

girneter의 이미지

struct S
{
    ~S() { cout << "~S()\n"; }
};

void i_will_throw() { throw 0; }

void f()
{
    //auto_ptr<S> ap(new S);
    S s;
    S* ptr = &s;

    i_will_throw();
}

이렇게 해도,
f()에서 예외가 발생하면 S의 소멸자가 호출되는 것을 확인할 수 있는데요.

개념없는 초딩들은 좋은 말로 할때 DC나 웃대가서 놀아라. 응?

htna의 이미지

함수의 파라메터로 들어가거나, 결과로 나오는 값이 객체일때 유용하겠군요...
복사생성자도 불리지 않구...

class CBase {
public:
	virtual ~CBase() {
	}
};

class CDerived : public CBase {
public:
	CDerived() {
		int k = 0;
	}
	virtual ~CDerived() {
		int k = 0;
	}
	int value[1000]; // burdensome !!!
};

auto_ptr<CBase> call()
{
	return auto_ptr<CBase>(new CDerived());
}


int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	auto_ptr<CBase> ptr = call();
}

WOW Wow!!!
Computer Science is no more about computers than astronomy is about telescopes.
-- E. W. Dijkstra

girneter의 이미지

아 그렇네요

한 함수가 heap 에 생성한 객체의 해제를
소유권 이전을 통해
다른 함수가 하도록 넘겨버리고
신경 끊을때 사용하면 되겠군요

개념없는 초딩들은 좋은 말로 할때 DC나 웃대가서 놀아라. 응?

doldori의 이미지

girneter wrote:
struct S
{
    ~S() { cout << "~S()\n"; }
};

void i_will_throw() { throw 0; }

void f()
{
    //auto_ptr<S> ap(new S);
    S s;
    S* ptr = &s;

    i_will_throw();
}

이렇게 해도,
f()에서 예외가 발생하면 S의 소멸자가 호출되는 것을 확인할 수 있는데요.


이런 경우에는 auto_ptr을 쓸 이유가 없지요.
S* ptr = new S;
했을 때와 비교해 보세요.
doldori의 이미지

girneter wrote:
한 함수가 heap 에 생성한 객체의 해제를
소유권 이전을 통해
다른 함수가 하도록 넘겨버리고
신경 끊을때 사용하면 되겠군요

하지만 auto_ptr을 함수 인자로 쓰는 것은 조심하셔야 합니다.
void f(auto_ptr<int> ap);

void g()
{
    auto_ptr<int> ap(new int);
    f(ap);
    *ap = 0;  // oops
}
죠커의 이미지

cinsk wrote:
CN wrote:
동적할당하지 않고 가상함수를 이용할 방법이 있나요? :-)

Virtual function의 사용과 dynamic memory allocation과는 별개로 알고 있습니다:

순간 잘못생각하고 답변을 했네요. 감사합니다.

htna의 이미지

girneter wrote:
void f(auto_ptr<int> ap);

void g()
{
    auto_ptr<int> ap(new int);
    f(ap);
    *ap = 0;  // oops
}

위와같이 사용하는것은 auto_ptr을 잘 못 이해하고 사용하는것과 같습니다.
(조심히 사용해야 하는것과는 별개라 생각이 드네요...)
auto_ptr에서 복사생성자를 호출하거나, 다른 auto_ptr에 대입을 하게되는 경우에 ownership을 이양하게 되어있습니다.

auto_ptr<C> ptr(new C); // ownership is given to ptr
auto_ptr<C> ptr2 = ptr; // ownership is transfered to ptr2
auto_ptr<C> ptr3;
ptr3 = ptr2; // ownership is transfered to ptr3

ptr->func(); // oops !!
ptr2->func(); // oops !!
ptr3->func(); // OK

와 같습니다.
즉 함수에 호출시 파라메터로 넘길때 복사해서 넘기게 되는경우에 자신의 ownership을 잃어버리게 되는 것입니다.
만약에 위와같이 함수호출 후에 계속 사용하고 싶다고 할 경우에는,
void f(auto_ptr<int>& ap);

void g()
{
    auto_ptr<int> ap(new int);
    f(ap);
    *ap = 0;  // OK now !!!
}

와 같이, reference로서 념겨야 할 것입니다.

WOW Wow!!!
Computer Science is no more about computers than astronomy is about telescopes.
-- E. W. Dijkstra

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.