问题描述
我阅读了以下链接:-
I read following links :-
我有一个问题我想澄清。
I have some question which i want to clarify.
1)给定POD类,例如:-
1) Given a POD class , say :-
class A{
int val;
};
如果我创建类型A的对象。
If i create an object of type A.
A obj; //将调用由编译器提供的隐式定义的构造函数吗?
现在据我所知,在这种情况下未调用构造函数。
A obj; // will this call implicitly defined constructor provided by compiler ?
Now as far as my understanding in this case constructor is not called.is it correct?
新A(); //值初始化A,这是零初始化,因为它是POD。
现在在这种情况下,将由编译器提供隐式定义的构造函数吗?
new A(); // value-initialize A, which is zero-initialization since it's a POD.Now in this case will implicitly defined constructor provided by compiler ? Is there is any role of constructor for zero initializing the object?
如果我的理解是错误的,请给我一个示例,其中不调用隐式定义的构造函数吗?全部。
If my understanding is wrong , could you please give me an example where implicitly defined defined constructor is not called at all.
谢谢。
推荐答案
1)正确。 obj.val
未初始化。
1) Correct. obj.val
is not initialized.
2)这是一个函数声明,而不是初始化:
2) This is a function declaration, not an initialization:
A obj(); // function obj() returning an A
如果这样做,
A obj{}; //C++11
A obj = A(); // C++03 and C++11
obj
将被值初始化, obj.val
也将被初始化。反过来,这意味着 obj.val
将被零初始化(( value-initialization 意味着 zero-初始化(针对内置类型)。
obj
would be value-initialized, and so would obj.val
. This in turn means that obj.val
would be zero-initialized (value-initialization means zero-initialization for built-in types).
这篇关于POD类对象初始化需要构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!