Question

Well visual studio gives me a warning. I do understand the warning & I do know it isn't an error. However I do not understand WHY I see the warning - and even worse I hence do not understand how to prevent/what potential problems it can give.

The code is written below, a function that should return a (const) reference to a std::function<> (fun_type_cref) by looking up the given "id" in a container.
The container is stored as [id, fun_type] pairs.

Handler::fun_type_cref Handler::Overwrite() const
{
    auto i(container.find(OVERWRITE));
    if (i != container.end()) {
        return *i;
    } else {
        return nullptr;
    }
}

THe exact warning occurs at both return statements is

warning C4172: returning address of local variable or temporary

What is causing this error? I am simply returning a reference to a contained object, right? *i won't create copy of the object, right? I can't see myself anywhere taking the address of something?

I could understand the second, as I return a reference to a locally created function object, however wasn't there a specific case for returning references to compile time constants or something like that?


EDIT: Well solved the first problem a simple type mismatch it seems as I forgot to actually return the correct part of the returned iterator - should've been return i->second. Strange visual studio did not give me a type mismatch error and that the compiler could convert a std::pair<std::string, std::function<...> > to a std::function<...>

Now the question has become about the second return part - I wish the function the return a "default value" (which would be a NO-OP) when the "OVERWRITE" id is not in the contained function table... How would one define such a thing? As I do not wish to return iterators...

Was it helpful?

Solution

try to replace return i by:

return (*i).second

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top