Take the 2-minute tour ×

I'm a bit confused about this:

I thought that if a pointer points to some object, assigning a dereference to some reference variable was a mere aliasing.


Object * p = &o;
Object & r = *p;
// r and o are the same object

I was aware there was some illegal cases, like:

Object * p = NULL;
Object & r = *p; // illegal

Now, what about the code below ?

const char * p = "some string";
const char & r = *p;


const char & r = *"some string";

I was said that this particular case involved temporary objects and, therefore I could'nt get the address of r and be sure it will point to a memory array containing my initial string.

What does C++ standard states about that case ? Is it another illegal case like the NULL provision, or is it allowed behavior.

In other words, is it legal or illegal (undefined behavior ?) to write something like ?

   char buffer[100];
   strcpy(buffer, &r);
share|improve this question
Are you referring to what I said about temporaries here? That happened because the reference was to a different type (unsigned char rather than char), and so a temporary of the correct type had to be created. In this case, you will get a reference to the first character in the string literal since the types match. –  Mike Seymour Nov 17 '11 at 17:18
@MikeSeymour: the case you pointed out is clear, as variables are of different type (even if I guess most compilers won't care and do it the same way, but that's not the point). But it made me think of that one and that I was not really as sure as I thought of the behavior when dereferencing to an array item, then going back to the array from the address of the reference. –  kriss Nov 17 '11 at 17:28
add comment

1 Answer

up vote 5 down vote accepted

That's fine.

The string literal's data buffer will exist for the duration of your program (usually in a special segment of the process memory).

[C++11: 2.14.5/8]: Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char`”, where n is the size of the string as defined below, and has static storage duration (3.7).

[C++11: 3.7.1/1]: All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program (3.6.2, 3.6.3).

After all, that's how keeping a pointer to it works! Recall that pointers don't magically extend object lifetime any more than do references.

share|improve this answer
(Any more than do references to non-const, that is.) –  Lightness Races in Orbit Nov 17 '11 at 17:22
Although it should probably be mentioned that r is a reference to the first character, not to the entire string. –  Mooing Duck Nov 17 '11 at 17:25
@MooingDuck: The type says that :D –  Lightness Races in Orbit Nov 17 '11 at 17:26
add comment

Your Answer


