Is there any warning, which allows us to know whether NRVO/RVO performed or not, in GCC?
I found that -fno-elide-constru
I am not aware of any gcc specific diagnostic message or other method that easily can solve your task. As you have found out, -fno-elide-constructors
will disable copy/move elisions, so you will know for sure that (N)RVO will not happen in that case at least.
However, a quick look at paragraph 31 in section 12.8 of this C++11 working draft states that:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization. This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
- in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value
...
- when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
...
When copy/move elision happen the local auto object is the same as the temporary (return) object, which in turn is the same as the "storage" object (where the return value is stored). So the local auto object is the same as the storage object, which means a pointer comparison will equal true. A simple example to demonstrate this:
#include
#include
std::vector testNRVO(int value, size_t size, const std::vector **localVec)
{
std::vector vec(size, value);
*localVec = &vec;
/* Do something here.. */
return vec;
}
int main()
{
const std::vector *localVec = nullptr;
std::vector vec = testNRVO(0, 10, &localVec);
if (&vec == localVec)
std::cout << "NRVO was applied" << std::endl;
else
std::cout << "NRVO was not applied" << std::endl;
}
Enabling/disabling -fno-elide-constructors
changes the printed message as expected. Note: in the strictest sense the pointer comparison might be depending on undefined behavior when (N)RVO does not happen, since the local auto object is non-existing.
Doing pointer comparisons will add cruft, but with the advantage of compiler-independency.