简体   繁体   English

了解新的运营商

[英]Understanding new operators

What happened if we invoke different forms of the operator new and operator delete? 如果我们调用不同形式的运算符new和operator delete会发生什么?

class A
{
public:
    void* operator new  ( std::size_t count, const char* msg );
};

void* A::operator new  ( std::size_t sz, const char* msg ){
    std::printf("global op new called, message = %s",msg);
    return std::malloc(sz);
}

int main(){
    A *a = new ("message") A;
    delete a;
}

Does the program have UB in that case? 在这种情况下,程序是否具有UB? What is Standard talking about that? 标准在说什么呢?

Yes, your code has undefined behaviour, in a number of ways. 是的,您的代码在许多方面都有未定义的行为。

In general terms, the result is undefined unless the form of release matches the form of allocation. 一般而言,除非发布形式与分配形式匹配,否则结果是不确定的。 That includes a mismatch of form of operator new. 这包括新运算符形式的不匹配。 (Placement new is a bit special and different, but I won't go there). (新的展示位置有些特殊且与众不同,但我不会去那里)。

Also, the OP's comments below the original post are 100% incorrect. 另外,OP在原始帖子下方的评论是100%不正确的。 There is no requirement that any form of operator new or operator delete use malloc() and free() (or related functions). 不需要任何形式的operator newoperator delete使用malloc()free() (或相关函数)。 Accordingly, the statement delete a has undefined behaviour, since it means that memory allocated using malloc() is released using the global operator delete() . 相应地,语句delete a具有未定义的行为,因为这意味着使用全局operator delete()释放使用malloc()分配的malloc()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM