0

I am trying to initialize all pointers in vector to NULL. Based on thread: initialize vector of pointers (automatically) and How to initialize a vector of pointers

I could just use the vector constructor to achieve what I want. My question is : is the initialization NULL pointer is a standard behaviour? Or the pointers in vector might not be NULL on some compiler? If initialize to NULL is standard, could anyone tell me in which chapter and section can I find the related info from c++ standard?

Thanks,

Rong

Community
  • 1
  • 1
r0n9
  • 2,505
  • 1
  • 29
  • 43

1 Answers1

6

I assume you mean something like this:

std::vector<MyClass*> v(10);

Yes, the vector is initialized with null pointers. Quoting the standard by chapter and verse is somewhat involved…

C++14 §23.3.6.2 “`vector constructors, copy, and assignment”:

explicit vector(size_type n, const Allocator& = Allocator());

Effects: Constructs a vector with n default-inserted elements using the specified allocator.

Requires: T shall be DefaultInsertable into *this.

§23.2.1 “General container requirements” ¶13:

T is DefaultInsertable into X means that the following expression is well-formed:

allocator_traits<A>::construct(m, p)

— An element of X is default-inserted if it is initialized by evaluation of the expression

allocator_traits<A>::construct(m, p)

where p is the address of the uninitialized storage for the element allocated within X.

§20.7.8.2 “Allocator traits member functions” ¶5:

template <class T, class... Args>
  static void construct(Alloc& a, T* p, Args&&... args);

Effects: calls a.construct(p, std::forward<Args>(args)...) if that call is well-formed; otherwise, invokes ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...).

§20.7.9.1 “[Default] allocator members” ¶12:

template <class U, class... Args>
  void construct(U* p, Args&&... args);

Effects: ::new((void *)p) U(std::forward<Args>(args)...)

Referring back to §23.2.1 ¶13, see that args is empty. Therefore…

§8.5 “Initializers”:

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

Same section:

To value-initialize an object of type T means: … otherwise, the object is zero-initialized.

Same section:

To zero-initialize an object or reference of type T means: … if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;106

Footnote 106:

As specified in 4.10, converting an integer literal whose value is 0 to a pointer type results in a null pointer value.

Community
  • 1
  • 1
rob mayoff
  • 375,296
  • 67
  • 796
  • 848