【问题标题】:Using smart_ptr for user defined class objects对用户定义的类对象使用 smart_ptr
【发布时间】:2013-06-17 14:09:09
【问题描述】:

作为一个试图理解智能指针的 C++ 新手。我已经写了下面的代码来检查。

它确实编译并运行了,但我希望调用我的类的析构函数并从析构函数中打印 cout,但它没有。

我们是否需要重载用户定义类中的任何函数,以便在该类的 smart_ptr 对象被销毁时调用其析构函数。

为什么它没有调用对象析构函数。我错过了什么?

#include <iostream>
#include <cstdlib>
#include <tr1/memory> 
#include <string>

//using namespace std;

class myclass
{
public:
  myclass();
  myclass(int);
  ~myclass();
private:
  int *ptr;
  std::string *cptr;
};

myclass::myclass()
{
    std::cout << "Inside default constructor\n";
}

myclass::myclass(int a)
{
   std::cout << "Inside user defined constructor\n" ;
   ptr = new int[10];
   cptr = new std::string("AD");
}

myclass::~myclass()
{
    std::cout << "Inside destructor..\n";
    delete [] ptr;
    delete cptr;

    std::cout << "Freed memory..\n";
}

int main()
{


   int i;
   std::cin >> i;       
 std::tr1::shared_ptr<std::string> smartstr(new std::string);
 std::tr1::shared_ptr<myclass> smart_a(new myclass(i));
   if(i == 0)
   {
      std::cout << "Exiting...\n";
      exit(-1);
   }


}

【问题讨论】:

  • 您是退出,还是只允许main 返回?它在两种情况下的行为是否相同?
  • 我想我会给 Goldenmean 一个发现差异的机会 :)
  • @Useless:我走下出口(-1)路径。但我从下面的答案中明白了这一点。
  • 为了完整起见,您应该将对 exit() 的调用替换为异常 throw。然后你会看到析构函数被调用了。
  • @juanchopanza:您还需要处理异常以确保堆栈已展开。

标签: c++ smart-pointers


【解决方案1】:

对象永远不会被销毁的原因是因为您正在通过调用exit 退出程序。这会导致程序在智能指针对象有机会超出范围之前退出,因此它们管理的对象永远不会被破坏。由于您在 main 中,因此请使用 return 语句而不是调用 exit

【讨论】:

    【解决方案2】:

    并且,作为其他答案的附加信息,请注意标准:

    根据 §3.6.1/4:

    在不离开当前块的情况下终止程序(例如,通过 调用函数std::exit(int) (18.5)) 不会破坏任何 具有自动存储持续时间的对象 (12.4)。

    【讨论】:

      【解决方案3】:

      在下面的代码中,

      if(i == 0)
      {
         std::cout << "Exiting...\n";
         exit(-1);
      }
      

      您正在通过调用exit() 来终止程序,因此该对象永远不会被销毁。所以从代码中删除exit(-1);

      【讨论】:

        【解决方案4】:

        一种可能的解决方案是确保在析构函数中刷新缓冲区。在你的析构函数中使用std::endl;。更多信息请看这里:Buffer Flushing, Stack Overflow

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-15
          相关资源
          最近更新 更多