c++ 默认构造函数 不同编译器debug和release的区别

这几年一直在linux上开发,用的gcc版本比较高,最近把gcc降到4.8.5(centos 7默认版本)后,出现了一些成员变量初始化的问题。

看示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

class Test
{
public:
    Test() = default;
    // Test(const Test& value) = default;
    // Test& operator=(const Test &value) = default;
    ~Test() = default;
    int GetA() { return m_a; }
    void SetA(int value) { m_a = value; }
private:
    int m_a;
};

int main(int argc, char **args)
{
    Test test;
    Test test2 = test;
    std::cout << test.GetA() << std::endl;
    std::cout << test2.GetA() << std::endl;
    test.SetA(1000);
    Test test3 = {};
    std::cout << test.GetA() << std::endl;
    std::cout << test3.GetA() << std::endl;
    Test test4 = {test};
    std::cout << test.GetA() << std::endl;
    std::cout << test4.GetA() << std::endl;
    return 0;
}
编译器debugrelease
gcc 4.82147483647或者-21474836480
gcc 800
gcc 9.300
vs2019 msvc 142随机数0
clang 7随机数随机数
clang 10 x861随机数
clang 10 x640随机数

gcc 4.8 好像不同硬件上会不一样,在另一 服务器上测试都为0

看来还是使用旧式显式初始化靠谱一些,或者这样int m_a = 0;进行显式初始化(需要编译器支持c++11)