簡體   English   中英

C ++:刪除了對象(使用new創建),但成員函數仍然有效(?)

[英]C++: object deleted (created with new) but member function still working (?)

出於好奇和實驗目的,我編寫了以下代碼,現在試圖了解刪除后發生的事情...為什么cat對象仍然發出聲音?

我使用的編譯器版本:

g++ (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609

並編譯代碼:

g++ cat.cpp -pedantic -Wall -o cat

與其他編譯器一起刪除后調用meou()可能會崩潰。

我想知道

  • 為什么不崩潰
  • 我應該采取哪些預防措施

編碼:

#include <iostream>
using namespace std;


class Cat
{
    public:
        Cat()  { cout << "Cat construct" << endl; }
        ~Cat() { cout << "Cat destruct" << endl; }
        void meow(); 
};

void Cat::meow(void)
{
    cout << "meow..." << endl;
}    

int main()
{
    Cat * pCat = new Cat;    
    pCat->meow();    
    cout << "pCat = " << pCat << endl;    
    delete pCat;    
    pCat = NULL;    
    cout << "pCat = " << pCat << endl;    
    pCat->meow();    
    cout << "why still meowing?!" << endl;    
    return 0;
}

輸出:

Cat construct
meow...
pCat = 0x2147030
Cat destruct
pCat = 0
meow...
why still meowing?!

為什么不崩潰

因為取消引用nullptr或訪問已刪除的對象是未定義的行為。 C ++不需要崩潰,但是崩潰可能是未定義行為的結果。

我應該采取哪些預防措施

那是一個相當廣泛的話題。 在C ++中,最重要的是不需要使用動態分配。 寫:

Cat cat;
cat.meow();

如果您不能這樣做,請使用std::unique_ptr

auto cat_ptr = std::make_unique<Cat>();
cat_ptr->meow();

如果您需要集合,請不要使用new[] 使用std::vector

std::vector<Cat> cats;
std::vector<std::unique_ptr<Cat>> cat_ptrs;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM