Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any scenarios where C4172 Visual C++ warning should not be considered an error?

There's C4172 Visual C++ warning for cases when a function returns an address of a local or temporary or a reference to a local variable.

Something like this:

int& fun()
{
    int var;
    return var; //C4172
}

Now looks like it is a good idea to use #pragma warning to make Visual C++ treat C4172 as error and break compilation.

Are there any sane scenarios where C4172 is not actually an error?

like image 980
sharptooth Avatar asked Feb 04 '13 15:02

sharptooth


2 Answers

I'm not sure why anyone would ever want to do this:

int * stackTester()
{
    int dummy;
    return &dummy;
}

bool stackGoesUp()
{
    int dummy;
    return stackTester() > &dummy;
}

But generally speaking, you should treat the warning like an error.

like image 95
IronMensan Avatar answered Nov 17 '22 07:11

IronMensan


It is a level 1 warning, very hard to ignore. But the compiler is following language standards here, invoking UB is not forbidden. And it is a very common bug that too often does come to a good end. The pointed-to stack location stays stable as long as you don't make any function calls.

The best way to deal with this is to always turn warnings into errors. Compile with /WX, "Treat warnings as errors" setting in the IDE. If you then intentionally want to suppress a warning then #pragma warning makes it clear to everybody that something fishy is going on that was thought about and not an accident.

like image 6
Hans Passant Avatar answered Nov 17 '22 05:11

Hans Passant