Returning a reference to a local temporary object when dereferencing a pointer

The Clang compiler generates a warning compiling this piece of code, and I cannot understand why.

const int* Get() { static const int ARRAY[4] = {1, 2, 3, 4}; return &ARRAY[0]; } const int& Test() { const auto& p = Get(); return (*p); } warning: returning reference to local temporary object [-Wreturn-stack-address] return (*p); 

GCC does not show any warnings about this code. I can fix the fragment as follows: const auto p = Get(); But I want to know if there is any temporary object, and the problem lies deeper.

+5
source share
2 answers

This warning is false positive, because the pointer p not temporary, even though p refers to it. There are more scenarios in which this warning is falsified; See Error 21218 , which uses

 char * f() { typedef char* t; const t & r = new char[5]; return r; } 

Presumably, if the return type is a reference, Clang looks for const references (related to temporary) in the returned expression, not considering how they are used.

+4
source

Answer: Clan warning is incorrect.

Let me go through what happens here:

  • static const int ARRAY[4] = {1, 2, 3, 4}; builds a global array int s
  • return &ARRAY[0]; returns a pointer to the first element of the global array
  • const auto& p = Get() stores a reference to a pointer to the first element of the global array
  • return (*p); creates a link to the lvalue of the first element of the global array

4 is complicated. Klang, apparently, incorrectly believes that *p is a local value, when in fact we know that it is global.

Important for this proof is the fact that *p returns an lvalue .

+1
source

Source: https://habr.com/ru/post/1236054/


All Articles