Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of a reference to first item of an array

Tags:

c++

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);
like image 567
kriss Avatar asked Nov 17 '11 17:11

kriss


1 Answers

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.

like image 148
Lightness Races in Orbit Avatar answered Sep 27 '22 01:09

Lightness Races in Orbit