我听说临时对象只能分配给常量引用.
但是这段代码给出了错误
#include <iostream.h>
template<class t>
t const& check(){
return t(); //return a temporary object
}
int main(int argc, char** argv){
const int &resCheck = check<int>(); /* fine */
typedef int& ref;
const ref error = check<int>(); / *error */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
得到的错误是 invalid initialization of reference of type 'int&' from expression of type 'const int'
考虑以下C++程序:
#include <iostream>
template<typename T>
class A
{
public:
explicit A(T& x) : x_(x){}
const T& get() { return x_; }
private:
T x_;
};
int main()
{
int x = 42;
A<int&>(x).get() = 43; // compiles fine, even though get() looks like it returns a const ref
std::cout << x << '\n';
}
Run Code Online (Sandbox Code Playgroud)
程序编译OK并输出43.这表明get()返回的看似const引用实际上是一个非const引用,因为它允许修改它引用的值.
是引用此行为的参考规则崩溃吗?
如何强制从get()返回的引用行为类似于const引用,也就是说,它不允许修改它引用的值?