默认构造函数(由编译器创建)是否初始化内置类型?
c++ constructor initialization default-constructor built-in-types
我不明白为什么我会这样做:
struct S {
int a;
S(int aa) : a(aa) {}
S() = default;
};
Run Code Online (Sandbox Code Playgroud)
为什么不说:
S() {} // instead of S() = default;
Run Code Online (Sandbox Code Playgroud)
为什么要为此引入一个新关键字?
我有模板化的gray_code类,它用于存储一些无符号整数,其基础位以格雷码顺序存储.这里是:
template<typename UnsignedInt>
struct gray_code
{
static_assert(std::is_unsigned<UnsignedInt>::value,
"gray code only supports built-in unsigned integers");
// Variable containing the gray code
UnsignedInt value;
// Default constructor
constexpr gray_code()
= default;
// Construction from UnsignedInt
constexpr explicit gray_code(UnsignedInt value):
value( (value >> 1) ^ value )
{}
// Other methods...
};
Run Code Online (Sandbox Code Playgroud)
在一些通用算法中,我写了这样的东西:
template<typename UnsignedInt>
void foo( /* ... */ )
{
gray_code<UnsignedInt> bar{};
// Other stuff...
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中,我期望bar零初始化,因此bar.value要进行零初始化.但是,在遇到意外错误之后,似乎bar.value用垃圾(确切地说是4606858)初始化而不是0u.这让我感到惊讶,所以我去了cppreference.com,看看上面那条线应该做什么......
根据我的内容,表单T object{};对应于 …