Why is my constructor with a non-const reference as an argument allowed to call with temporary objects?

I have an example code below.

#include<iostream> template<typename T> class XYZ { private: T & ref; public: XYZ(T & arg):ref(arg) { } }; class temp { int x; public: temp():x(34) { } }; template<typename T> void fun(T & arg) { } int main() { XYZ<temp> abc(temp()); fun(temp()); //This is a compilation error in gcc while the above code is perfectly valid. } 

In the above code, although the XYZ constructor accepts the argument as a non-const reference, it compiles fine and the fun function does not compile. Is this specific to the g ++ compiler or the C ++ standard, have something to say about this?

Edit:

g ++ -v gives this.

gcc version 4.5.2 (Ubuntu / Linaro 4.5.2-8ubuntu4)

+7
source share
2 answers
  XYZ<temp> abc(temp()); 

It compiles because it is NOT a variable declaration. I'm sure you think this is a variable declaration when the fact is that it is a function declaration. Function Name abc ; the function returns an object of type XYZ<temp> and takes one (unnamed) argument, which, in turn, is a function that returns the type temp and does not accept arguments. See these topics for a detailed explanation:

And fun(temp()) does not compile, because temp() creates a temporary object, and the temporary object cannot be bound to a non-constant reference.

So this is the fix: specify your function template as:

 template<typename T> void fun(const T & arg) //note the `const` { } 
+12
source

No, the standard does not allow passing a temporary link not const. (C ++ 0X introduces a link to rvalue to allow this in some controlled cases), see 8.5.3 / 5 (which is too long for me, the link to the significant part otherwise, the link must be to the unstable type const, but you should read the entire list of cases to know that they are not applicable here).

AND

 XYZ<temp> abc(temp()); 

- just another example of the most unpleasant parsing.

+5
source

All Articles