c 中的向量析构函数-ag捕鱼王app官网

c 中的向量析构函数

作者:迹忆客 最近更新:2023/03/31 浏览次数:

本文讨论了析构函数及其在 c 中创建向量和字符串时的用途。


c 中的析构函数

在 oop 范例中,析构函数是与每个类相关联的成员函数,只要类的对象被删除或其生命周期结束,它就会自动执行。 此外,为在堆内存上创建的所有变量调用析构函数。

删除此类变量时,将调用析构函数,以便释放内存供以后使用。

析构函数的创建名称与类名称相同,并带有平铺符号前缀 (~)。 在一个类中,使用构造函数创建的每个对象都通过使用析构函数删除,但顺序与创建顺序相反。

析构函数的语法是:

~ ()
{
    //coding
}

让我们考虑一个示例类。

#include
using namespace std;
class destructorexample
{
public:
    destructorexample(){
      cout<<"in constructor of destructorexample"<<endl;
      }
      ~destructorexample(){
      cout<<"in destructor of destructorexample";
    }
};
int main(){
  destructorexample t;
  return 0;
}

这将给出以下输出。

in constructor of destructorexample
in destructor of destructorexample

c 中向量和字符串的析构函数

如果您使用 std::vectorstd::string ,则当它们的对象超出范围时会自动调用析构函数。 这些类实现了析构函数,当需要删除相应的对象时会自动触发析构函数。

所以你不需要显式地调用它们或实现它们。

但是如果你有一个指向某个类的指针向量,那么这些对象需要像这样显式删除:

#include 
#include 
using namespace std;
class myclass
{
    public:
    myclass()
    {
        cout << "object created" << endl;
    }
    ~myclass()
    {
        cout << "object destroyed" << endl;
    }
};
int main()
{
  vector testvec;
  // creating the objects
  myclass* p = null;
  for (int i = 0; i < 3; i  )
  {
      p = new myclass();
      testvec.push_back(p);
  }
  // destroying the objects
  for (auto p: testvec)
  {
      delete p;
  }
  testvec.clear();
  return 0;
}

输出结果如下:

object created
object created
object created
object destroyed
object destroyed
object destroyed

我们遍历向量并显式删除每个对象。 堆中的内存已被释放; 因此,我们可以使用 .clear() 方法删除向量的所有元素。

现在应该明确删除 myclass* 对象; vector 不会删除这些对象。 因此,你可以说,如果向量中有简单的类对象,这些对象将被自动删除。

但是,如果您有一个指针,则必须明确删除它。

上一篇:

下一篇:在 c 中实现 realpath() 函数

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

arduino 中停止循环

发布时间:2024/03/13 浏览次数:444 分类:c

可以使用 exit(0),无限循环和 sleep_n0m1 库在 arduino 中停止循环。

arduino 复位

发布时间:2024/03/13 浏览次数:315 分类:c

可以通过使用复位按钮,softwarereset 库和 adafruit sleepydog 库来复位 arduino。

发布时间:2024/03/13 浏览次数:181 分类:c

可以使用简单的方法 toint()函数和 serial.parseint()函数将 char 转换为 int。

arduino 串口打印多个变量

发布时间:2024/03/13 浏览次数:381 分类:c

可以使用 serial.print()和 serial.println()函数在串口监视器上显示变量值。

arduino if 语句

发布时间:2024/03/13 浏览次数:123 分类:c

可以使用 if 语句检查 arduino 中的不同条件。

arduino icsp

发布时间:2024/03/13 浏览次数:214 分类:c

icsp 引脚用于两个 arduino 之间的通信以及对 arduino 引导加载程序进行编程。

发布时间:2024/03/13 浏览次数:151 分类:c

可以使用 arduino 中的循环制作计数器。

使用 c 编程 arduino

发布时间:2024/03/13 浏览次数:127 分类:c

本教程将讨论使用 arduino ide 在 c 中对 arduino 进行编程。

arduino 中的子程序

发布时间:2024/03/13 浏览次数:168 分类:c

可以通过在 arduino 中声明函数来处理子程序。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图