gpt4 book ai didi

c++ - 析构函数很懒惰,为什么?

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:43 25 4
gpt4 key购买 nike

真正销毁对象的是什么?如果您这样做:

class K {
public:
K (int m) {v = m;}
int v;
};


Class * x = reinterpret_cast <K*> (:: operator new (sizeof (K)));
new ((void *) x) K (2);


x-> ~ C ();
cout << x-> v; / / result: 2

:: operator delete ((void *) v);

解构器什么也没做! (?)为什么?

最佳答案

您正在处理两组想法:

  1. 对象的构建和销毁
  2. 分配和释放内存。

了解如何正确组合它们很重要。

假设你有一个函数:

void f1()
{
// Construct an object.
// The constructor gets called.
K k(10);

// Do something with the object.

// Done with the function
// The object k gets destructed.
// The destructor gets called.
}

在此函数中,您将在堆栈上构造对象。当您从函数返回时,析构函数会自动调用。内存会自动为您从堆栈中分配和释放。

现在,让我们看看另一个函数。

void f2()
{
// Allocate memory for the object.
// Use that Construct an object .
// The constructor gets called.
K* k = new K(10);

// Do something with the object.

// Done with the function
// Delete the object.
// The destructor gets called.
// Deallocate the memory.
delete k;
}

此函数中的 K* k = new K(10); 行执行两个操作——它从堆中为对象分配内存以及调用构造函数来构造对象。

delete k; 也结合了两个操作。它首先调用析构函数,然后从堆中释放内存。如果您没有 delete k;,该函数将泄漏由 new K(10) 分配的内存。

在这里,我们使用了 newdelete 运算符。

现在看看如何使用全局 operator newoperator delete 函数。

void f3()
{
// Allocate memory for the object from the heap.
void* p = ::operator new(sizeof(K));

// At this point, an object of type K has not been constructed yet.

K* k1 = reinterpret_cast<K*>(p);
// Using the reinterpret_cast to treat the `void*` as a `K*` does not
// change that fact. An object of type K has not yet been constructed still.

K* k2 = new (p) K(10);
// Use placement new operator to construct K.
// At this point, an object of type K has been constructed by calling
// K's constructor using the memory pointed to by p.


// Do something with the object.

// Done with the function.
// Now it's time to do the necessary things to release resources back to
// the system.

// Do not use `delete K` at this point.
// Whenever you use the placement new operator, call the destructor explicitly.
// This calls the destructor ~K(), but does not deallocate memory from heap.
k2->~K();

// Deallocate the memory heap.
::operator delete(p);
}

关于c++ - 析构函数很懒惰,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22442548/

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