对用户定义的类对象使用smart_ptr 作为一个C++新手,试图理解智能指针。我写了下面的代码来检查

对用户定义的类对象使用smart_ptr 作为一个C++新手,试图理解智能指针。我写了下面的代码来检查,c++,smart-pointers,C++,Smart Pointers,它确实编译并运行了,但我希望调用类的析构函数并从析构函数打印cout,但它没有 我们是否需要重载用户定义类中的任何函数,以便在该类的smart_ptr对象被销毁时调用其析构函数 为什么它没有调用对象析构函数呢。我错过了什么 #include <iostream> #include <cstdlib> #include <tr1/memory> #include <string> //using namespace std; class myc

它确实编译并运行了,但我希望调用类的析构函数并从析构函数打印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);
   }


}
#包括
#包括
#包括
#包括
//使用名称空间std;
类myclass
{
公众:
myclass();
myclass(int);
~myclass();
私人:
int*ptr;
std::string*cptr;
};
myclass::myclass()
{

std::cout一种可能的解决方案是确保在析构函数中刷新缓冲区。在析构函数中使用
std::endl;
。有关更多信息,请查看此处:

对象从未被销毁的原因是,您正在通过调用
退出退出程序。这会导致程序在智能po之前退出inter对象有可能超出范围,因此它们所管理的对象永远不会被销毁。由于您在
main
中,请使用return语句,而不是在下面的代码中调用
exit

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

标准::cout以及标准中的注释,作为其他答案的补充信息:

根据§3.6.1/4:

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


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