bug-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

So a reference to temporary must be const? why?


From: Brian Clarkson
Subject: So a reference to temporary must be const? why?
Date: Tue, 25 Jan 2005 12:04:38 +0900

Hello.

I came across this problem while porting some code from vc++ to gcc.
From my shaky understanding of the ANSI C++ standard, temporaries are guaranteed to stick around at least until right before execution of the next line (or up until the semicolon). However, it seems that a non-const reference to a temporary is forbidden. Isn' t this way too strict?

I have distilled the issue to the following example:

****begin test.cpp****

#include <iostream>
using namespace std;

class vector {
public:
        vector(int x_, int y_) : x(x_), y(y_) {}
        vector(const vector& xx) : x(xx.x), y(xx.y) {}
vector& operator=(const vector& xx) { x = xx.x; y = xx.y; return *this; }

        friend vector operator+(const vector& a, const vector& b);
public:
        int x, y;
};

vector operator+(const vector& a, const vector& b) {
//      vector tmp(a.x + b.x, a.y + b.y);
//      return tmp;
        return vector(a.x + b.x, a.y + b.y);
}

void f(vector& v)
{
        cout << "vector = (" << v.x << ", " << v.y << ")" << endl;
}

int main()
{
        vector  a(1, 2);
        vector  b(2, 3);
        
        f(a+b); // this line generates an error

        return 0;
}

****end test.cpp****

Which when compiled gives the following output:

 g++ test.cpp

test.cpp: In function `int main()':
test.cpp:32: error: could not convert `operator+(const vector&, const
   vector&)((&b))' to `vector&'
test.cpp:23: error: in passing argument 1 of `void f(vector&)'


If f() is defined as f(const vector&) then this example compiles, but it seems to me that operating on a reference to the temporary that is generated from (a+b) should be safe since we are finished with it before the semicolon.

Is there a better way to do this? (i.e. no explicit temporaries and no unnecessary copies)

Thanks in advance.

Brian





reply via email to

[Prev in Thread] Current Thread [Next in Thread]