Re: Nonstandard Extension Used?
On Friday, February 1, 2013 5:28:59 PM UTC-6, SG wrote:
Am 01.02.2013 23:44, schrieb Nephi Immortal:
Why do C++ Compiler generates an error to report nonstandard extension?
Because you did not write valid ISO C++ Code.
The reference is used to avoid to allocate more temporary memory and more numbers of copy constructors are reduced.
main.cpp(1383): warning C4239: nonstandard extension used : 'argument' : conversion from 'Data' to 'Data &'
You tried to initialize a mutable lvalue reference with an rvalue
expression. This is not allowed according to the ISO C++ standard.
Data Func()
{
Data temp;
return temp;
}
Let's revise my code below.
Data &&Func()
{
Data temp;
return static_cast< Data&& >( temp );
}
Data &&Func2( Data &&d )
{
return static_cast< Data&& >( d );
}
Func() allocates temp into its stack. The memory address is assumed to be
0x12FF00. Left value reference is converted into right value reference.
Before exiting Func(), Destructor is called, but memory address: 0x12FF00
stays in stack.
Func2() is called more than two times while right value reference forwards
the same memory address: 0x12FF00. After returning back to main(), Copy
Constructor is called and copies all data members into variable x as
main()'s stack. Then all the data members in memory address: 0x12FF00 is
removed from the Func()'s stack.
Please confirm if my code is correct.
int main()
{
Data x = Func2( Func2( Func() ) );
return 0;
}
Func() is an rvalue expression because you return an object by value.
Func2 takes a mutable lvalue reference.
This is what's wrong with your program.