c++ - MS Visual C++ 2010 错误 : On provision of default destructor

标签 c++ visual-studio-2010 destructor

我在提供默认析构函数时遇到运行错误。但是,如果让编译器提供默认析构函数,它就会安全运行。

class foo
{
    private:
    int m_size;
    int* m_array;

    public:
    foo( int a_size ):m_size( a_size ), m_array( new int(a_size) ){}

    ~foo() {
        delete [] m_array;  
    }   
    void setArray();
};

void foo::setArray() 
{
    for( int i=0; i<m_size; ++i )
        m_array[i] = 10*i;
}

int main( int argc, const char* argv[] )
{
    class foo obj( 6 );
    obj.setArray();
    system( "pause" );
    return 0;
}

运行时错误:

这可能是由于堆损坏,这表明 Destructors.exe 或它加载的任何 DLL 中存在错误。

这也可能是由于用户在 Templates.exe 具有焦点时按了 F12。

输出窗口可能有更多的诊断信息。

谢谢。

最佳答案

new int(a_size)动态分配单个 int初始值为 a_size .

我想你的意思是new int[a_size]它动态分配一个数组 a_size int

(你还应该为你的 foo 类提供一个复制构造函数和复制赋值运算符,因为默认的类不会做正确的事情。最好用 m_array 替换你的指针成员 std::vector<int> 来管理自动动态分配的内存,然后您就不必担心用户定义的析构函数、复制构造函数和复制赋值运算符。)

关于c++ - MS Visual C++ 2010 错误 : On provision of default destructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4550809/

相关文章:

c - C中不一致的声明和定义

ruby - Ruby 中的终结器 : is there an equivalent to "__destruct" from PHP?

c++ - 非常基础的英语语法解析器

c++ - 多态性和默认值 : can co-exist?

c++ - 使用 PCLVisualizer 可视化 PCL 1.6 的网格

c++ - 在构造函数完成之前调用析构函数是否合法?

c++ - union 成员的析构函数似乎被自动调用

c++ - Boost.asio使用协程实现多个连接的echo服务器

c++ - setData 为 QAbstractProxyModel 返回 false

visual-studio - 在 visual studio 10 中同时重命名多个文件?