c++ 结构是否有默认构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8280023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does a c++ struct have a default constructor?
提问by morpheus
I wrote the following code snippet:
我写了以下代码片段:
void foo()
{
struct _bar_
{
int a;
} bar;
cout << "Value of a is " << bar.a;
}
and compiled it with g++ 4.2.1 (Mac). The output is "Value of a is 0".
并用 g++ 4.2.1 (Mac) 编译它。输出是“a 的值为 0”。
Is it true to say that data members of a struct in c++ are always initialized by default (compared to c)? Or is the observed result just coincidence?
说 c++ 中结构的数据成员总是默认初始化是真的吗(与 c 相比)?还是观察到的结果只是巧合?
I can imagine that structs in c++ have a default constructor (since a struct and a class is almost the same in c++), which would explain why the data member a of bar is initialized to zero.
我可以想象 c++ 中的结构有一个默认构造函数(因为 c++ 中的结构和类几乎相同),这将解释为什么 bar 的数据成员 a 被初始化为零。
回答by Martin York
The simple answer is yes.
It has a default constructor.
简单的答案是肯定的。
它有一个默认构造函数。
Note: struct and class are identical (apart from the default state of the accesses specifiers).
注意:struct 和 class 是相同的(除了访问说明符的默认状态)。
But whether it initializes the members will depends on how the actual object is declared. In your example no the member is not initialized and a has indeterminate value.
但是它是否初始化成员将取决于实际对象的声明方式。在您的示例中 no 成员未初始化并且 a 具有不确定的值。
void func()
{
_bar_ a; // Members are NOT initialized.
_bar_ b = _bar_(); // Members are zero-initialized
// From C++14
_bar_ c{}; // New Brace initializer (Members are zero-initialized)
_bar_* aP = new _bar_; // Members are NOT initialized.
_bar_* bP = new _bar_(); // Members are zero-initialized
// From C++14
_bar_ cP = new _bar_{}; // New Brace initializer (Members are zero-initialized)
}
// static storage duration objects
// i.e. objects at the global scope.
_bar_ c; // Members are zero-initialized.
The exact details are explained in the standard at 8.5 Initializers [dcl.init]
paragraphs 4-10. But the following is a simplistic summary for this situation.
标准的8.5 Initializers [dcl.init]
第 4-10 段解释了确切的细节。但以下是对这种情况的简单总结。
A structure without a user defined constructor has a compiler generated constructor. But what it does depends on how it is used and it will either default initialize its members (which for POD types is usually nothing) or it may zero initialize its members (which for POD usually means set its members to zero).
没有用户定义构造函数的结构具有编译器生成的构造函数。但是它的作用取决于它的使用方式,它要么默认初始化其成员(对于 POD 类型通常什么都没有),要么它可以将其成员初始化为零(对于 POD 通常意味着将其成员设置为零)。
PS. Don't use a _
as the first character in a type name. You will bump into problems.
附注。不要使用 a_
作为类型名称中的第一个字符。你会遇到问题。
回答by Alok Save
Is it true to say that data members of a struct in c++ are always initialized by default (compared to c)? Or is the observed result just coincidence?
说 c++ 中结构的数据成员总是默认初始化是真的吗(与 c 相比)?还是观察到的结果只是巧合?
It is a coincidence.
这是一个巧合。
Your code invokes Undefined Behavior; unless you explicitly set the members to 0
they can be anything.
您的代码调用未定义行为;除非您明确地将成员设置为0
它们可以是任何东西。
回答by David Rodríguez - dribeas
Not an answer, but you might take it to be... if you want to try it:
不是答案,但您可能会认为它是...如果您想尝试一下:
void foo() {
struct test {
int value;
} x;
std::cout << x.value << std::endl;
x.value = 1000;
}
int main() {
foo();
foo();
}
In your example, the memory already had the 0
value before the variable was created, so you can call it a lucky coincidence(in fact, some OS will zero out all memory before starting a process, which means that 0 is quite a likely value to find in a small short program...), the previous code will call the function twice, and the memory from the first call will be reused in the second one, chances are that the second time around it will print 1000. Note however that the value is still undefined, and that this test might or not show the expected result (i.e. there are many things that the compiler can do and would generate a different result...)
在您的示例中,内存0
在创建变量之前已经具有该值,因此您可以称其为幸运的巧合(实际上,某些操作系统会在启动进程之前将所有内存清零,这意味着 0 很可能是find in a small short program...),前面的代码将调用该函数两次,并且第一次调用的内存将在第二次调用中重用,第二次可能会打印 1000。但是请注意该值仍未定义,并且此测试可能会或不会显示预期结果(即编译器可以执行许多操作并会生成不同的结果......)
回答by Igor Oks
Member variables of a struct are notinitialized by default. Just like a class (because a struct is exactly the same thing as a class, only in struct the members are public by default).
默认情况下不初始化结构的成员变量。就像一个类(因为结构体与类完全相同,只有在结构体中成员默认是公共的)。
回答by 111111
Do not rely on this functionality it is non-standard
不要依赖此功能,它是非标准的
just add
只需添加
foo() : a() {}
I can't remember the exact state of gcc 4.2 (i think it is too old) but if you were using C++11 you can do the following
我不记得 gcc 4.2 的确切状态(我认为它太旧了)但是如果您使用的是 C++11,您可以执行以下操作
foo()=default;