相关疑难解决方法(0)

在c ++中使用typedef和templates进行常量引用

我听说临时对象只能分配给常量引用.

但是这段代码给出了错误

#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++ templates const reference temporary

15
推荐指数
3
解决办法
4434
查看次数

为什么C++ const引用可以被拼写为非const引用

考虑以下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引用,也就是说,它不允许修改它引用的值?

c++ templates const reference

9
推荐指数
1
解决办法
186
查看次数

标签 统计

c++ ×2

const ×2

reference ×2

templates ×2

temporary ×1