Is circumventing a class' constructor legal or does it result in undefined behaviour?

后端 未结 7 498
甜味超标
甜味超标 2020-11-29 11:06

Consider following sample code:

class C
{
public:
    int* x;
};

void f()
{
    C* c = static_cast(malloc(sizeof(C)));
    c->x = nullptr; // &         


        
相关标签:
7条回答
  • 2020-11-29 11:57

    This particular code is fine, because C is a POD. As long as C is a POD, it can be initialized that way as well.

    Your code is equivalent to this:

    struct C
    {
       int *x;
    };
    
    C* c = (C*)malloc(sizeof(C)); 
    c->x = NULL;
    

    Does it not look like familiar? It is all good. There is no problem with this code.

    0 讨论(0)
提交回复
热议问题