【问题标题】:question about auto_ptr::reset关于 auto_ptr::reset 的问题
【发布时间】:2010-07-17 18:49:43
【问题描述】:

谁能解释一下this code from C++ Reference site:

#include <iostream>
#include <memory>
using namespace std;

int main () {
  auto_ptr<int> p;

  p.reset (new int);
  *p=5;
  cout << *p << endl;

  p.reset (new int);
  *p=10;
  cout << *p << endl;

  return 0;
}

【问题讨论】:

    标签: c++ pointers smart-pointers auto-ptr


    【解决方案1】:

    auto_ptr 管理一个指针。 reset 将删除它拥有的指针,并指向别的东西。

    所以你从auto_ptr p 开始,没有指向任何东西。当您使用resetnew int 时,它不会删除任何内容,然后指向动态分配的int。然后将 5 分配给该 int

    然后你再次reset,删除之前分配的int,然后指向一个新分配的int。然后将 10 分配给新的 int

    当函数返回时,auto_ptr 超出范围并调用其析构函数,这会删除最后分配的int,程序结束。

    【讨论】:

    • 'auto_ptr 管理一个指针'——这真的正确还是它管理了指针指向的资源?
    • @Chubsdad:我会说它是正确的,就像在int *p = new int; delete p; 中一样,我们通常说最后一个表达式“删除p”,而我们真正的意思是“它删除了指向的资源”通过p"。
    【解决方案2】:

    也许这个例子会更好:

    struct tester {
       int value;
       tester(int value) : value(value) 
       { std::cout << "tester(" << value << ")" << std::endl; }
       ~tester() { std::cout << "~tester(" << value << ")" << std::endl; }
    };
    int main() {
       std::auto_ptr<tester> p( new tester(1) ); // tester(1)
       std::cout << "..." << std::endl;
       p.reset( new tester(2) );                 // tester(2) followed by ~tester(1)
       std::cout << "..." << std::endl;
    }                                         // ~tester(2)
    

    重要的一行是将新指针传递给 reset 方法。在输出中您可以看到tester 的构造函数被调用,然后将指针传递给reset 方法,自动指针处理先前管理的内存并删除输出中显示~tester(1) 的对象。同样,在函数结束时,自动指针超出范围,它会处理存储的指针打印~test(2)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 2021-11-29
      • 2011-09-22
      • 2018-05-23
      • 2011-11-16
      相关资源
      最近更新 更多