Search code examples
c++compiler-warningssuppress-warnings

Suppress "Avoid unnamed object" warnings for function returns


I have a log function that I sometimes pass the return of on to another function, and sometimes call alone

LogReturnStruct Log(string message) { writeToFile(message); return {message};);

this is because i sometimes want to log something is about to be attempted, as well as if it succeeded or not

void Handle(LogReturnStruct, statusCode)
{
    if(statusCode == valid)
        Log("sucess: "+ LogReturnStruct.message);
    else
        Log("failure: "+ LogReturnStruct.message);
}

So i can call something like this

Handle(Log("message"),funcThatMightFail());

and it will enforce logging before and after this call, and will log at least before even if the call raises an exception

I also want to be able to just log a message however

Log("message"); // alone call

However, no matter how i use [[maybe_unused]], i can't seem to suppress the compiler warning

"Avoid unnamed objects with custom creation and destruction"

is there a way to indicate this return value may be unused (and that's ok) without disabling the entire warning?


Solution

  • It seems you might use [[gsl::suppress(es.84)]], but it should be used at call site :-/

    MACRO can then help:

    LogReturnStruct LogImpl(string message) { writeToFile(message); return {message}; }
    
    #define Log(s) [[gsl::suppress(es.84)]] LogImpl(s)
    

    Cleaner solution is to avoid the warning and create 2 functions (You already have them :) ) (but requires to change call sites):

    void Handle(LogReturnStruct, statusCode)
    {
        if(statusCode == valid)
            writeToFile("sucess: "+ LogReturnStruct.message);
        else
            writeToFile("failure: "+ LogReturnStruct.message);
    }
    

    and

    Handle(Log("message"), funcThatMightFail());