I got this class:
class myClass
{
private:
struct tm minDate, maxDate;
public:
myClass();
struct tm GetMinDate() {return minDate;};
struct tm GetMaxDate() {return maxDate;};
};
and this function call
SetMinMaxDate(struct tm *MinDate, struct tm *MaxDate);
the follwing code
myClass myInstance;
SetMinMaxDate(&myInstance.GetMinDate(), &myInstance.GetMaxDate());
Works well and with MSVC 2010 and 2005 no warnings are generated. But if i compile it with intel C++ i get the warning
warning #1563: taking the address of a temporary
According to this related thread
The lifetime of the temporary object (also known as an rvalue) is tied to the expression and the destructor for the temporary object is called at the end of the full expression
SetMinMaxDate copies the content passed with pointers. The pointer itself is not stored. So the 2 temporary tm elements should be valid until SetMinMaxDate has returned.
Is there a problem in this code or is this a false positive of intel C++?
EDIT: I found another very interesting post that gives a reason for this behavior: Why is it illegal to take the address of an rvalue temporary?
It is a valid warning because SetMinMaxDate()
makes no guarantees that it will not store that pointer for later use. And since you are passing a pointer to a temporary, if SetMinMaxDate
stored it for later use, it would be a problem.
Another reason for the warning is that with the declaration you have, maybe SetMinMaxDate
is modifying the tm structs passed in via pointer and such modifications would get lost since it is a pointer to a temp object.
SetMinMaxDate
would be better declared as:
SetMinMaxDate(const struct tm & MinDate, const struct tm & MaxDate);
there would be no warning in this case. The const
lets the compiler know it will not be modifying the object and the &
indicates that it is unlikely to be trying to store the address for later.