考虑下面的代码,调用 onData 回调,然后我将 const 引用分配给一个变量。我想了解它是如何工作的。有人告诉我你不能修改 const 引用,但在这里看起来你可以通过分配给一个非常量变量。
void onData(const evpp::TCPConnPtr &socket) {
evpp::TCPConnPtr connection = socket;
}
在实际应用中,我将其分配给对象实例的成员变量。
答案 0 :(得分:1)
简单来说,引用只是被引用对象的别名。当引用为 const
时,表示您不能通过该引用修改对象(可以通过其他方式修改对象,这种区别很重要,尤其是在多线程中)。复制 const
引用就像复制被引用的对象:
std::string x = "foo";
const std::string& x_const_ref = x; // constant reference to x
// x can be modifed but not via x_const_ref
//x_const_ref = "moo"; // ERROR !
x = "bar"; // OK !
std::string y = x; // y is initialized with a copy of x
std::string z = x_const_ref; // z is initialized with a copy of x
y
和 z
都将保存字符串 "bar"
,尽管 x
在最后两行中没有被修改。如果 TCPConnPtr
没有奇怪的复制构造函数,那么这基本上也是您的代码中发生的情况(如果它确实尝试修改 socket
,您将收到编译器错误)。