int a=int(); what happens in C++98?

微笑、不失礼 提交于 2019-12-09 16:30:36

问题


Please read the question entirely before you think to mark it as duplicate. The statement like

int i=int();

most programmers will say that there is value initialization here & i will be value initialized. (0 as output). But it also prints 0 as output on C++98 compiler. Following program that I tested on C++98 implementation and gives me 0 as output.

#include <iostream>
int main()
{
     int i=int();
     std::cout<<i;
}

Don't say that i is value initialized in above C++98 program ,because value initialization introduced in C++03. So How i is initialized here? Is it really constructor call? int() looks like constructor call. Primitive types have also default constructors in C++ as said by Bjarne stroustrup in his book C++ programming language & TC++PL.

The C++ programming language Bjarne stroustrup:

10.4.2 Built in types also have default constructors

also read section 6.2.8 of same book.

The following links also says that built in types have default constructors in C++.

1) http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=15

2) http://www.geeksforgeeks.org/c-default-constructor-built-in-types/

So can I really say that it is a constructor call of the integer type?


回答1:


5.2.3 Explicit type conversion (functional notation)

2 The expression T(), where T is a simple-type-specifier (7.1.5.2) for a non-array complete object type or the (possibly cv-qualified) void type, creates an rvalue of the specified type, whose value is determined by default-initialization (8.5; no initialization is done for the void() case). [...]

8.5 Initializers

5 [...] To default-initialize an object of type T means:

-- if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

-- if T is an array type, each element is default-initialized;

-- otherwise, the storage for the object is zero-initialized.

There is no problem. int() has been guaranteed to evaluate to zero right from the very first C++ standard. The fact that it happened through default-initialization, rather than value-initialization, is a technical detail that is completely irrelevant for your question.



来源:https://stackoverflow.com/questions/30603512/int-a-int-what-happens-in-c98

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!