Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added further information to the CS on dynamic initialization

...

In this compliant solution, the memory is properly initialized to the value 12 prior to printing its value:

Code Block
bgColor#ccccff
langcpp
#include <iostream>
 
void f() {
  int *i = new int;
  *i = 12;
  std::cout << i << ", " << *i;
}

Another acceptable form of initialization is to place empty parenthesis or empty curly braces after the type being allocated. This causes direct initialization of the pointed-to object to occur, which will zero-initialize the object if the initialization omits a value. For instance:

Code Block
int *i = new int(); // zero-initializes *i
int *j = new int{}; // zero-initializes *j
int *k = new int(12); // initializes *k to 12
int *l = new int{12}; // initializes *k to 12

Noncompliant Code Example

...