Does C++ do value initialization of a POD typedef?

前端 未结 2 1509
栀梦
栀梦 2020-12-28 22:08

Does C++ do value initialization on simple POD typedefs?

Assuming

typedef T* Ptr;

does

Ptr()

do v

2条回答
  •  生来不讨喜
    2020-12-28 22:54

    #include 
    struct Foo {
        char bar;
        char baz;
        char foobar;
        // the struct is a POD
        //virtual void a() { bar='b'; }
    };
    
    int main() {
        Foo o1;
        Foo o2 = Foo();
    
        std::cout << "O1: " << (int)o1.bar <<" "<< (int)o1.baz <<" "<< (int)o1.foobar << std::endl;
        std::cout << "O2: " << (int)o2.bar <<" "<< (int)o2.baz <<" "<< (int)o2.foobar << std::endl;
        return 0;
    }
    

    Output:

    O1: -27 -98 0

    O2: 0 0 0

    Adding () propagates initializer calls to all POD members. Uncomenting the virtual method changes output to:

    O1: -44 -27 -98

    O2: -71 -120 4

    However adding destructor ~Foo() does not suppress the initialization, although it creates non-POD object (output similar to first one).

提交回复
热议问题