问题
I read following links :-
object initialized with and without parentheses
types of default constructor
diff b/w value,zero and default intilization
I have some question which i want to clarify.
1) Given a POD class , say :-
class A{
int val;
};
If i create an object of type A.
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?
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.
Thank you in advance.
回答1:
1) Correct. obj.val
is not initialized.
2) This is a function declaration, not an initialization:
A obj(); // function obj() returning an A
If you did this,
A obj{}; //C++11
A obj = A(); // C++03 and C++11
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).
回答2:
A obj;
It calls default constructor (or even not for optimization), however default constructor doesn't initialize it.
A obj();
It's a function declaration. No arguments and returns A
.
A obj{};
Instead, you can use above code which sets val
to zero.
来源:https://stackoverflow.com/questions/19912200/does-pod-class-object-initialization-require-constructor