【问题标题】:C++ Destruction Class Error Occur发生 C++ 破坏类错误
【发布时间】:2012-05-09 14:07:19
【问题描述】:

执行时这个程序有什么问题,我想破坏类,但是程序结束我在 cout fetch 后看到错误框。 有什么问题?

#include <iostream>
using namespace std;

class user {

    public:int internal;
    public:user(int point) {
               internal = point;
           };

           ~user () {
               cout << "Fetch";
           }
    };



void main() {
    user gil(5);
    user * p;
    p=&gil;
    delete p;
    getchar();
}

【问题讨论】:

标签: c++ oop class


【解决方案1】:

在未从new 接收到的指针上调用delete 是未定义的行为。 IOW,你的代码错了,不要那样做,gil 有自动存储,无论如何都会自动销毁(duh)。

【讨论】:

    【解决方案2】:

    您的代码有一个未定义的行为。您正在调用 delete 上未分配有 new 的指针。
    一旦你有一个未定义的行为,所有的赌注都没有了,任何行为都是可能的。

    一旦创建对象的作用域{}结束,自动(堆栈)存储上的对象将被释放,无需为它们调用delete

    【讨论】:

      【解决方案3】:

      试试:

      #include <iostream>
      using namespace std;
      
      class user 
      {
      public:
        int internal;
        user(int point) 
        {
          internal = point;
        }
      
        ~user() 
        {
          cout << "Fetch" << endl;
        }
      };
      
      int main() 
      {
        user* p = new user(5);
        cout << p->internal << endl;
        delete p;
        return 0;
      }
      

      为了避免使用new/delete 并在变量超出范围时将其销毁:

      #include <iostream>
      using namespace std;
      
      class user 
      {
      public:
        int internal;
        user(int point) 
        {
          internal = point;
        }
      
        ~user() 
        {
          cout << "Fetch" << endl;
        }
      };
      
      int main() 
      {
        user p(5);
        cout << p.internal << endl;
        return 0;
      }
      

      【讨论】:

      • @Bill 请注意其他答案和 cmets,因为它们可以很好地了解此问题的原因。编程时牢记它们可以避免很多头痛。
      • 为了推荐 new/delete 而不是仅仅使用自动变量,很诱人。
      • @JohnDibling 我添加了您似乎担心的替代方法。
      【解决方案4】:

      您创建的类将被自动销毁,因为它是在堆栈上分配的。您不需要在其上使用删除运算符。但如果你只想调用析构函数,你可以这样做:

      gil.~user();
      

      但我不建议这样做。

      【讨论】:

      • @BillGates:不,你没有。你可能认为你有,但你没有。
      猜你喜欢
      • 2015-02-19
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 2022-10-14
      • 2018-12-14
      • 2013-08-05
      • 2017-08-18
      • 1970-01-01
      相关资源
      最近更新 更多