有和没有主体的 C++ 部分构造函数表现不同
C++ partial constructors with and without a body behave differently
考虑以下 C++ 代码:
#include <iostream>
#include <string>
#define DUMP(_, str) do { \
std::cout << str; \
for (int i = 0; i < 10; ++i) \
std::cout << (_).x[i] << std::endl; \
std::cout << "a = " << (_).a << std::endl; \
std::cout << "b = " << (_).b << std::endl; \
std::cout << "c = " << (_).c << std::endl; \
std::cout << "d = " << (_).d << std::endl; \
std::cout << std::endl; \
} while (0)
//#define ENABLE_WTF
struct A {
int x[10];
float a, b, c, d;
#ifndef ENABLE_WTF
A() : d(4) { DUMP(*this, "=== INSIDE CTOR ===\n"); }
#else
A() : d(4) {}
#endif
};
int main() {
A a;
DUMP(a, "=== OUT OF CTOR ===\n");
}
可以看出,A
有一个只初始化其中一个字段的部分构造函数,而所有其他字段可以预见地仍然是垃圾; demonstration here.
现在的问题是:当部分构造函数没有主体(demonstration here)时,将 A
的其余部分置零是特定于编译器的,还是 C++ 本身的一部分?
使用给定的构造函数
A() : d(4) { ... }
除了d
之外的所有数据成员都将被默认初始化。对于内置类型,这是空操作,并且这些数据成员将具有不确定的值。读取它们的值是未定义的行为。
一些编译器 might initialize 调试构建中的此类数据成员具有特定的字节模式,以帮助捕获运行时错误。
考虑以下 C++ 代码:
#include <iostream>
#include <string>
#define DUMP(_, str) do { \
std::cout << str; \
for (int i = 0; i < 10; ++i) \
std::cout << (_).x[i] << std::endl; \
std::cout << "a = " << (_).a << std::endl; \
std::cout << "b = " << (_).b << std::endl; \
std::cout << "c = " << (_).c << std::endl; \
std::cout << "d = " << (_).d << std::endl; \
std::cout << std::endl; \
} while (0)
//#define ENABLE_WTF
struct A {
int x[10];
float a, b, c, d;
#ifndef ENABLE_WTF
A() : d(4) { DUMP(*this, "=== INSIDE CTOR ===\n"); }
#else
A() : d(4) {}
#endif
};
int main() {
A a;
DUMP(a, "=== OUT OF CTOR ===\n");
}
可以看出,A
有一个只初始化其中一个字段的部分构造函数,而所有其他字段可以预见地仍然是垃圾; demonstration here.
现在的问题是:当部分构造函数没有主体(demonstration here)时,将 A
的其余部分置零是特定于编译器的,还是 C++ 本身的一部分?
使用给定的构造函数
A() : d(4) { ... }
除了d
之外的所有数据成员都将被默认初始化。对于内置类型,这是空操作,并且这些数据成员将具有不确定的值。读取它们的值是未定义的行为。
一些编译器 might initialize 调试构建中的此类数据成员具有特定的字节模式,以帮助捕获运行时错误。