class Example
{
boost::shared_ptr<FilterProvider> filterProvider;
public:
void RegisterFilter(const boost::shared_ptr<FilterProvider>& toRegister)
{
filterProvider = toRegister;
}
const boost::shared_ptr<const FilterProvider>& GetFilter() const
{
return filterProvider; // Compiler reports "Returning address of local
// variable or temporary"
}
};
I don’t see what’s local or temporary about filterProvider here; I’m returning what looks like a member variable of the class, not a temporary. (If I was actually returning a local variable or something like that the warning would make sense)
The specific warning is:
warning C4172: returning address of local variable or temporary.
Your shared ptr is declared with type
You are returning
by const reference. See the difference?
The types are not the same, but the former is convertible to the latter, and the compiler invokes the conversion. The result of the conversion is not an lvalue, but rather a temporary object, meaning that you are returning a const reference bound to a temporary object. This is legal initialization-wise, but the temporary will be destroyed right before the function returns. So in the calling code the reference will be invalid, which is what the compiler is warning you about.