C++ 禁止用戶使用 new 的方式創(chuàng)建堆對象

C++ 中可以通過重載 new 和 delete 操作符,來禁止用戶使用 new 的方式創(chuàng)建堆對象的,但是我認(rèn)為是沒有辦法完全禁止用戶創(chuàng)建堆對象的,因為用戶依然可以使用 malloc 的方式創(chuàng)建堆對象,并操作類。

#include <QCoreApplication>
#include <QDebug>

namespace {
const QString OUTPUT_INFO_SATRT("CreatStackOnly===debug output:");
}

class CreatStackOnly {
    void* operator new(size_t) throw() { return nullptr;}
    void operator delete(void*){}
public:
    explicit CreatStackOnly(int number = 0)
        : testNumber(number)
    {
        qDebug() << OUTPUT_INFO_SATRT << "CreatStackOnly() called";
    }
    ~CreatStackOnly() {
        qDebug() << OUTPUT_INFO_SATRT << "~CreatStackOnly() called";
    }
    void testFuction() {
        qDebug() << OUTPUT_INFO_SATRT << "testNumber = " << testNumber;
        qDebug() << OUTPUT_INFO_SATRT << "testFuction() called";
    }
    void setNumber(int number) {
        testNumber = number;
    }
private:
    int testNumber = 0;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    CreatStackOnly * test = (CreatStackOnly*) malloc(sizeof (CreatStackOnly));
    test->testFuction();
    free(test);
    test->testFuction();
    test = nullptr;
    test = (CreatStackOnly*) malloc(sizeof (CreatStackOnly));
    test->setNumber(2020);
    test->testFuction();

    return a.exec();
}

此時當(dāng)我們使用 new 操作符號時的編譯器給出的錯誤提示信息:

使用 new 操作符號時的錯誤提示信息

上述測試示例的輸出結(jié)果:

使用 malloc 方法創(chuàng)建堆對象以及測試輸出

上面的示例中體現(xiàn)出如下信息:

  1. new/delete 操作符號可以被重載,malloc/free 是庫函數(shù),不能重載;
  2. new/delete 執(zhí)行過程中會調(diào)用構(gòu)造/析構(gòu)函數(shù),malloc/free 只是面無表情的堆空間分配和釋放機器。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容