Compiler detection of return link to local variable

I have just been bitten by the unpleasant undefined behavior due to returning a link to a local variable.

We know this evil, and as a rule, the compiler prints nice warningto tell us so ... well, gcc (3.4.2) does not seem to push the checks too hard.

std::string get_env_value(std::string const& key);

std::string const& get_phase()
{
  std::string const& phase = get_env_value("PHASE"); // [1]
  std::cout << "get_phase - " << phase << '\n';
  return phase;                                      // [2]
}

This compiles without crashing, and yet we find ourselves in an unpleasant area of ​​undefined behavior.

The string [1]is fine, because the standard indicates that the lifetime of a variable associated with a constant reference must be extended to match the lifetime of the const reference.

The string [2]also looks fine ...

  • Do the C ++ specifications comply with this case?
  • - , ? ( - ...)

, , " " [1], [2] , , ...

+5
2

[2]. r , rvalue, .

, , , , . ++ , , , .

+5
  • , , Standard / .

  • VS 2010 (/Za,/W4).

, .

, , :

std::string const& get_phase() 
{ 
    std::string const& phase = get_env_value("PHASE"); // [1] 
    std::cout << "get_phase - " << phase << '\n'; 

    if(1){
        while(1){
            return phase;
        }
    }
    return phase;                                      // [2] 
} 

VS .

, , , , . (, VS) .

int get_phase() 
{
    char ch;
    if(ch){
        return 0;
    }
     // nothing returned from here.
} 

, , OP , , , , , . , .

$6.6.3/2 - " return ; undefined ."

OP, , , , , , , . , , . , undefined

+2

All Articles