Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

c++ - Why is returning a reference to a function local value not a compile error?

The following code invokes undefined behaviour.

int& foo()
{
  int bar = 1234;
  return bar;
}

g++ issues a warning:

warning: reference to local variable ‘bar’ returned [-Wreturn-local-addr]

clang++ too:

warning: reference to stack memory associated with local variable 'bar' returned [-Wreturn-stack-address]

Why is this not a compile error (ignoring -Werror)?

Is there a case where returning a ref to a local var is valid?

EDIT As pointed out, the spec mandates this be compilable. So, why does the spec not prohibit such code?

question from:https://stackoverflow.com/questions/26296665/why-is-returning-a-reference-to-a-function-local-value-not-a-compile-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would say that requiring this to make the program ill-formed (that is, make this a compilation error) would complicate the standard considerably for little benefit. You'd have to exactly spell out in the standard when such cases shall be diagnosed, and all compilers would have to implement them.

If you specify too little, it will not be too useful. And compilers probably already check for this to emit warnings, and real programmers compile with -Wall_you_can_give_me -Werror anyway.

If you specify too much, it will be difficult (or impossible) for compilers to implement the standard.

Consider this class (for which you only have the header and a library):

class Foo
{
  int x;

public:
  int& getInteger();
};

And this code:

int& bar()
{
  Foo f;
  return f.getInteger();
}

Now, should the standard be written to make this ill-formed or not? Probably not, what if Foo is implemented like this:

#include "Foo.h"

int global;

int& Foo::getInteger()
{
  return global;
}

At the same time, it could be implemented like this:

#include "Foo.h"

int& Foo::getInteger()
{
  return x;
}

Which of course would give you a dangling reference.

My point is that the compiler cannot really know whether returning a reference is OK or not, except for a few trivial cases (returning a reference to a function-scope automatic variable or parameter of non-reference type). I don't think it's worth it to complicate the standard for that. Especially as most compilers already warn about this as a quality-of-implementation matter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...