In the general case, there seems to be no way to disable the binding of a temporary to a constant reference.
However, to give a reasonable answer, I would like to cite the C ++ 2003 standard:
If the initializer expression is an rvalue, and T2 is the class type, and "cv1 T1" is a reference with "cv2 T2", the link is bound in one of the following ways (the choice is determined by the implementation):
- The link is attached to the object represented by rvalue (see 3.10), or to a sub-object within this object.
- The temporary type "cv1 T2" [sic] is created, and the constructor is called to copy the entire rvalue object to the temporary one. The link is attached to a temporary or to a sub-object within the temporary. 93)
The constructor that will be used to create the copy must be called regardless of whether the copy is actually executed.
Thus, it might seem that this can be achieved in C ++ 03 by making a private copy constructor:
struct A { A() {} private: A(const A&); }; int main() { const A& a = A(); }
However, this will not work with popular compilers. For example, GCC accepts the above code even with the -std=c++03 flag. Klang also accepts this code, but with a warning:
test.cc:8:12: warning: C ++ 98 requires an accessible copy constructor for class 'A' when linking a temporary reference; was closed
Thus, contrary to the standard, there is no way to do this.
C ++ 11 in this case no longer needs an accessible copy constructor.
vitaut
source share