V
V.Subramanian, India
The following post is for learning purpose only.
I am using g++ 3.4.3
Consider the following program x.cpp
#include <cstdlib>
#include <iostream>
#include <ostream>
using namespace std;
class Test {
public:
explicit Test(int arg = 0);
Test& operator+=(const Test& rhs);
int value() const;
private:
int x;
};
inline Test::Test(int arg) : x(arg)
{
}
inline Test& Test:perator+=(const Test& rhs)
{
x += rhs.value();
return *this;
}
inline int Test::value() const
{
return x;
}
inline const Test operator+(const Test& lhs,
const Test& rhs)
{
Test temp(lhs);
return temp += rhs;
}
int main()
{
Test x(100);
Test y(200);
const Test* p = &(x + y);
int a = 10;
int b = 20;
const int* i = &(a + b);
return EXIT_SUCCESS;
}
When I compile this program x.cpp as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp
I get the following warning and error.
x.cpp: In function `int main()':
x.cpp:42: warning: taking address of temporary
x.cpp:46: error: non-lvalue in unary `&'
x.cpp:42: warning: unused variable 'p'
x.cpp:46: warning: unused variable 'i'
Question:
In the above code, why does the compiler give warning for
taking the address of temporary-class-object namely
(x + y) whereas it generates error for taking the address of
temporary-built-in-object namely (a + b) ? I expected error
message for taking &(x + y) similar to that of &(a + b).
Is ithis behaviour specific to g++3.4.3 ? Or the standard
itself requires so ?
Please explain.
Thanks
V.Subramanian
I am using g++ 3.4.3
Consider the following program x.cpp
#include <cstdlib>
#include <iostream>
#include <ostream>
using namespace std;
class Test {
public:
explicit Test(int arg = 0);
Test& operator+=(const Test& rhs);
int value() const;
private:
int x;
};
inline Test::Test(int arg) : x(arg)
{
}
inline Test& Test:perator+=(const Test& rhs)
{
x += rhs.value();
return *this;
}
inline int Test::value() const
{
return x;
}
inline const Test operator+(const Test& lhs,
const Test& rhs)
{
Test temp(lhs);
return temp += rhs;
}
int main()
{
Test x(100);
Test y(200);
const Test* p = &(x + y);
int a = 10;
int b = 20;
const int* i = &(a + b);
return EXIT_SUCCESS;
}
When I compile this program x.cpp as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp
I get the following warning and error.
x.cpp: In function `int main()':
x.cpp:42: warning: taking address of temporary
x.cpp:46: error: non-lvalue in unary `&'
x.cpp:42: warning: unused variable 'p'
x.cpp:46: warning: unused variable 'i'
Question:
In the above code, why does the compiler give warning for
taking the address of temporary-class-object namely
(x + y) whereas it generates error for taking the address of
temporary-built-in-object namely (a + b) ? I expected error
message for taking &(x + y) similar to that of &(a + b).
Is ithis behaviour specific to g++3.4.3 ? Or the standard
itself requires so ?
Please explain.
Thanks
V.Subramanian