gpt4 book ai didi

c++ - 将 smart_ptr 用于用户定义的类对象

转载 作者:太空狗 更新时间:2023-10-29 19:39:26 25 4
gpt4 key购买 nike

作为一个试图理解智能指针的 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);
}


}

最佳答案

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

关于c++ - 将 smart_ptr 用于用户定义的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17149613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com