c++ - 运算符 new/delete 和析构函数

标签 c++ visual-c++ memory-management destructor

所以我是一个试图掌握新运算符的初学者。我的析构函数有什么问题?

class arr{
public:
    arr(){
        pool=::operator new(100*sizeof(double));
    }
    ~arr(){
        ::operator delete(pool);
    }
    void* pool;
};

int main()
{
    arr a;
    a.~arr(); //If I comment this out it's ok.

    void* pool2=::operator new(100*sizeof(double)); //Works
    ::operator delete(pool2); //Fine.

    system("pause");
    return 0;
}

离开a.~arr();在给我这个错误:

调试断言失败!文件:dbgdel.cpp 行:52

表达式:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

我不明白为什么 pool2 工作正常,但使用这个类给我带来了问题。此外,错误仅在系统“暂停”后弹出,即在调用 a.~arr() 之后???

谢谢!

最佳答案

好吧,乍一看,您不应该显式调用析构函数。而是使用范围来强制超出范围并调用析构函数。

int main()
{
    {
        arr a;
    } //This calls destructor of a

    //Rest of code
}

否则,a 的析构函数会被调用两次:一次是在您调用它时,另一次是在 a 超出范围时。

编辑:

给你。

http://www.parashift.com/c++-faq-lite/dtors.html

关于c++ - 运算符 new/delete 和析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4737403/

相关文章:

c++ - vector 下标超出 vector vector 的范围

c++ - Direct2D:将 ID2D1Image 转换为 ID2D1Bitmap

c++ - 为什么 strlen() 在 VC++ 调试器中似乎返回 <void>?

c内存泄漏问题

c - 为二维数组分配内存

c++ - 抽象类是抽象数据类型的一个例子吗?

android - 在 Eclipse 中使用 JNI 构建 OpenCV 应用程序

c++ - 为 CUDA 实现 32 位内存集的 'right' 方法是什么?

visual-studio-2010 - VS2010 C和C++-强制ANSI兼容以实现Linux/gcc兼容性吗?

linux - 使用 mmap 复制文件