Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unary + on pointers

I was just browsing through the draft of the C++11 standard and found the following puzzling statement (§13.6/8):

For every type T there exist candidate operator functions of the form

T* operator+(T*);

How should this "unary +" operator on pointer be understood? Is this just a no-op in the normal case, which can nevertheless be overloaded? Or is there some deeper point I am missing here?

like image 295
LiKao Avatar asked Feb 13 '12 19:02

LiKao


1 Answers

The + on pointers is a noop except for turning things to rvalues. It sometimes is handy if you want to decay arrays or functions

int a[] = { 1, 2, 3 };
auto &&x = +a;

Now x is an int*&& and not an int(&)[3]. If you want to pass x or +a to templates, this difference might become important. a + 0 is not always equivalent, consider

struct forward_decl;
extern forward_decl a[];
auto &&x = +a; // well-formed
auto &&y = a + 0; // ill-formed

The last line is ill-formed, because adding anything to a pointer requires the pointer's pointed-to class type to be completely defined (because it advances by sizeof(forward_decl) * N bytes).

like image 157
Johannes Schaub - litb Avatar answered Jan 05 '23 01:01

Johannes Schaub - litb