简体   繁体   中英

C++ default constructor for primitives?

So it's my understanding that if I have SomeType foo , the default constructor for SomeType will be invoked and foo will be initialized. But if I have int x -- this is undefined according to the spec. Why isn't the default constructor ( int() ) invoked?

Why isn't the default constructor ( int() ) invoked?

The language did not want to impose the cost of calling the constructor and intializing such objects if the programmer wanted them to be left uninitialized.

A clarification:

int x;

does not cause undefined behavior. Using x without initializing it or setting the value explicitly is cause for undefined bahavior.

One example

That allows a programmer to allocate large chunks of memory as buffer that can be used later to intialize objects using placement new .

char* buffer = new char[SOME_LARGE_BUFFER_SIZE];

and later

// Construct an object in dynamically allocated memory, buffer.
SomeObject* obj = new (buffer+offset) SomeObject;

Given the usage of buffer , initializing every element of buffer is of no value to the user. The cost of initializing such objects is unnecessary imposition given the use case.

Your intuition is actually right. In hindsight int x; being uninitialized (and also SomeType foo; can leave some members uninitialized) is a constant source of bugs and security bugs. The rational was, as R Sahu pointed out to "not pay for what you don't need" which is a core philosophy of C++. Now it might seem laughable that initializing a local int variable could be the source of performance concern, especially with today optimizers, but in the old days it was.

Today there is still a need to have variables uninitialized after they are defined (think for instance of arrays that you need to fill afterwards). But the way it's handled in C++ is unfortunate (in hindsight).

A better option would have been to not allow uninitialized variables unless the programmer explicitly asks for it, eg:

int x = unitialized; // where uninitialized is a keyword

... again, in hindsight.


Today almost all guidelines recommend to always initialize your variables and to do that you can employ some tricks:

  • always use {} to initialize your variables, eg int x{};
  • (almost) always use auto which forces you to have initializations, eg auto x = int{};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM