5

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.

Example:

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;

or

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);
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
kriss
  • 23,497
  • 17
  • 97
  • 116
  • 2
    Are you referring to what I said about temporaries [here](http://stackoverflow.com/questions/8122517/casting-c-string-to-unsigned-char-pointer/8122581#8122581)? 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

1 Answers1

5

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055