Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does value initialization of a pointer do in C++?

Tags:

c++

I have seen the related answers here and here on this, but I wanted confirmation, because none of them make this explicit.

Suppose I have a class Foo and a member bar of type int*.

Are the following two initializations entirely equivalent?

Foo::Foo() : bar(NULL) // null pointer constant by macro
{
}

Foo::Foo() : bar() // value initialization
{
}
like image 917
merlin2011 Avatar asked Jul 17 '14 23:07

merlin2011


People also ask

What does initializing a value mean?

In computer programming, initialization (or initialisation) is the assignment of an initial value for a data object or variable. The manner in which initialization is performed depends on the programming language, as well as the type, storage class, etc., of an object to be initialized.

Why is it important to initialize your pointer variable to null?

You are definitely encouraged to set pointers to NULL whenever the alternative is your pointer having an indeterminate value. Usage of pointers with an indeterminate value is undefined behavior, a concept that you might not grasp properly if you're used to C programming and come from higher level languages.

Do pointers need to be initialized?

All pointers, when they are created, should be initialized to some value, even if it is only zero. A pointer whose value is zero is called a null pointer. Practice safe programming: Initialize your pointers!

What happens when you add a value to a pointer?

Pointer arithmetic and arrays. Add an integer to a pointer or subtract an integer from a pointer. The effect of p+n where p is a pointer and n is an integer is to compute the address equal to p plus n times the size of whatever p points to (this is why int * pointers and char * pointers aren't the same).


1 Answers

Value-initialization of a pointer initializes it to a null pointer value; therefore both initializer lists are equivalent.


Pointers don't have class or array type, so value initialization for them is zero initialization. (8.5p8)

Then, (8.5p6)

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

This integer literal 0 is a null pointer constant (4.10p1), which when converted to a pointer type creates a null pointer value.


Note that zero-initialization of variables with static and thread duration (3.6.2) also initializes pointers to null pointer values.


Above paragraph references are from C++1y draft n3936, but they were the same in earlier drafts I checked also.

like image 58
Ben Voigt Avatar answered Oct 24 '22 23:10

Ben Voigt