Pointer declaration
Declares a variable of a pointer or pointer-to-member type.
Contents |
[edit] Syntax
A pointer declaration is any simple declaration whose declarator has the form
* attr (optional) cv (optional) declarator
|
(1) | ||||||||
nested-name-specifier * attr (optional) cv (optional) declarator
|
(2) | ||||||||
S
.C
of type determined by the declaration specifier sequence S
.nested-name-specifier | - | a sequence of names and scope resolution operators ::
|
attr | - | (since C++11) a list of attributes |
cv | - | const/volatile qualification which apply to the pointer that is being declared (not to the pointed-to type, whose qualifications are part of declaration specifier sequence) |
declarator | - | any declarator |
There are no pointers to references and there are no pointers to bit-fields. Typically, mentions of "pointers" without elaboration do not include pointers to (non-static) members.
[edit] Pointers
Every value of pointer type is one of the following:
- a pointer to an object or function (in which case the pointer is said to point to the object or function), or
- a pointer past the end of an object, or
- the null pointer value for that type, or
- an invalid pointer value.
A pointer that points to an object represents the address of the first byte in memory occupied by the object. A pointer past the end of an object represents the address of the first byte in memory after the end of the storage occupied by the object.
Note that two pointers that represent the same address may nonetheless have different values.
struct C { int x, y; } c; int* px = &c.x; // value of px is "pointer to c.x" int* pxe= px + 1; // value of pxe is "pointer past the end of c.x" int* py = &c.y; // value of py is "pointer to c.y" assert(pxe == py); // == tests if two pointers represent the same address // may or may not fire *pxe = 1; // undefined behavior even if the assertion does not fire
Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior. Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault.
[edit] Pointers to objects
A pointer to object can be initialized with the return value of the address-of operator applied to any expression of object type, including another pointer type:
int n; int* np = &n; // pointer to int int* const* npp = &np; // non-const pointer to const pointer to non-const int int a[2]; int (*ap)[2] = &a; // pointer to array of int struct S { int n; }; S s = {1}; int* sp = &s.n; // pointer to the int that is a member of s
Pointers may appear as operands to the built-in indirection operator (unary operator*), which returns the lvalue expression identifying the pointed-to object:
int n; int* p = &n; // pointer to n int& r = *p; // reference is bound to the lvalue expression that identifies n r = 7; // stores the int 7 in n std::cout << *p; // lvalue-to-rvalue implicit conversion reads the value from n
Pointers to class objects may also appear as the left-hand operands of the member access operators operator->
and operator->*
.
Because of the array-to-pointer implicit conversion, pointer to the first element of an array can be initialized with an expression of array type:
int a[2]; int* p1 = a; // pointer to the first element a[0] (an int) of the array a int b[6][3][8]; int (*p2)[3][8] = b; // pointer to the first element b[0] of the array b, // which is an array of 3 arrays of 8 ints
Because of the derived-to-base implicit conversion for pointers, pointer to a base class can be initialized with the address of a derived class:
struct Base {}; struct Derived : Base {}; Derived d; Base* p = &d;
If Derived
is polymorphic, such a pointer may be used to make virtual function calls.
Certain addition, subtraction, increment, and decrement operators are defined for pointers to elements of arrays: such pointers satisfy the LegacyRandomAccessIterator requirements and allow the C++ library algorithms to work with raw arrays.
Comparison operators are defined for pointers to objects in some situations: two pointers that represent the same address compare equal, two null pointer values compare equal, pointers to elements of the same array compare the same as the array indices of those elements, and pointers to non-static data members with the same member access compare in order of declaration of those members.
Many implementations also provide strict total ordering of pointers of random origin, e.g. if they are implemented as addresses within continuous virtual address space. Those implementations that do not (e.g. where not all bits of the pointer are part of a memory address and have to be ignored for comparison, or an additional calculation is required or otherwise pointer and integer is not a 1 to 1 relationship), provide a specialization of std::less for pointers that has that guarantee. This makes it possible to use all pointers of random origin as keys in standard associative containers such as std::set or std::map.
[edit] Pointers to void
Pointer to object of any type can be implicitly converted to pointer to (possibly cv-qualified) void; the pointer value is unchanged. The reverse conversion, which requires static_cast
or explicit cast, yields the original pointer value:
int n = 1; int* p1 = &n; void* pv = p1; int* p2 = static_cast<int*>(pv); std::cout << *p2 << '\n'; // prints 1
If the original pointer is pointing to a base class subobject within an object of some polymorphic type, dynamic_cast
may be used to obtain a void* that is pointing at the complete object of the most derived type.
Pointers to void have the same size, representation and alignment as pointers to char.
Pointers to void are used to pass objects of unknown type, which is common in C interfaces: std::malloc returns void*, std::qsort expects a user-provided callback that accepts two const void* arguments. pthread_create
expects a user-provided callback that accepts and returns void*. In all cases, it is the caller's responsibility to cast the pointer to the correct type before use.
[edit] Pointers to functions
A pointer to function can be initialized with an address of a non-member function or a static member function. Because of the function-to-pointer implicit conversion, the address-of operator is optional:
void f(int); void (*p1)(int) = &f; void (*p2)(int) = f; // same as &f
Unlike functions or references to functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, etc.
void (a[10])(int); // Error: array of functions void (&a[10])(int); // Error: array of references void (*a[10])(int); // OK: array of pointers to functions
Note: declarations involving pointers to functions can often be simplified with type aliases:
using F = void(int); // named type alias to simplify declarations F a[10]; // Error: array of functions F& a[10]; // Error: array of references F* a[10]; // OK: array of pointers to functions
A pointer to function can be used as the left-hand operand of the function call operator, this invokes the pointed-to function:
int f(int n) { std::cout << n << '\n'; return n * n; } int main() { int (*p)(int) = f; int x = p(7); }
Dereferencing a function pointer yields the lvalue identifying the pointed-to function:
int f(); int (*p)() = f; // pointer p is pointing to f int (&r)() = *p; // the lvalue that identifies f is bound to a reference r(); // function f invoked through lvalue reference (*p)(); // function f invoked through the function lvalue p(); // function f invoked directly through the pointer
A pointer to function may be initialized from an overload set which may include functions, function template specializations, and function templates, if only one overload matches the type of the pointer (see address of an overloaded function for more detail):
template<typename T> T f(T n) { return n; } double f(double n) { return n; } int main() { int (*p)(int) = f; // instantiates and selects f<int> }
Equality comparison operators are defined for pointers to functions (they compare equal if pointing to the same function).
[edit] Pointers to members
[edit] Pointers to data members
A pointer to non-static member object m
which is a member of class C
can be initialized with the expression &C::m exactly. Expressions such as &(C::m) or &m inside C
's member function do not form pointers to members.
Such a pointer may be used as the right-hand operand of the pointer-to-member access operators operator.* and operator->*:
Pointer to data member of an accessible unambiguous non-virtual base class can be implicitly converted to pointer to the same data member of a derived class:
struct Base { int m; }; struct Derived : Base {}; int main() { int Base::* bp = &Base::m; int Derived::* dp = bp; Derived d; d.m = 1; std::cout << d.*dp << ' ' << d.*bp << '\n'; // prints 1 1 }
Conversion in the opposite direction, from a pointer to data member of a derived class to a pointer to data member of an unambiguous non-virtual base class, is allowed with static_cast
and