Question

I think both of the two functions are problematic because they return reference/pointer to local variable allocated in stack:

int &func1() {
   int a = 3; 
   return a;
}
int *func2() {
    int a = 3;
    int *p = &a;
    return p;
}

but when I use compile command g++ -Wall, why it only gives warning for func1 but not func2? Is it because func2 could be intentionally used for some purpose or the warning could be set by adding other parameter? My g++ version is 4.6.3, on Ubuntu 12.04.

Était-ce utile?

La solution

There is no way for the compiler to know what you are trying to do with the pointer you are returning in func2.

You could as well be returning an instance for an array, for example:

int *func2() {
    int a = 3;
    int *p = &a;
    /*some useful stuff*/
    if (some_criteria)
        p = new int[10];
    return p;
}

Because the compiler does not have the power to evaluate the semantics of the returned pointer.

Autres conseils

Per @kebs above gcc.gnu.org/onlinedocs/gcc/Warning-Options.html, there is an option (-Wno-return-local-addr) that sort of does this, enabled by default with -Wall (I checked).

However, I had something like

    char * foo(string bar) {
      return bar.c_str();
    }

No warning. But bar is a copy so a local value that is silently returned despite -Wall.

Should have had extr &

    char * foo(string &bar) {
      return bar.c_str();
    }

Wasted hours tracking that down in a large program that almost always worked correctly.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top