简体   繁体   English

如何将 const 引用分配给非 const 变量?

[英]How can you assign a const reference to a non const variable?

Consider following code, onData callback invoked and then I assign the const reference to a variable.考虑以下代码,调用 onData 回调,然后我将 const 引用分配给一个变量。 I want to understand how it works.我想了解它是如何工作的。 I was told you can't modify const references but here it looks like you can by assigning to a non-const variable.有人告诉我你不能修改 const 引用,但在这里看起来你可以通过分配一个非常量变量来修改。

void onData(const evpp::TCPConnPtr &socket) {
   evpp::TCPConnPtr connection = socket;
}

In real world application, I assign this to Object Instance's member variable.在实际应用中,我将其分配给 Object Instance 的成员变量。

In simple terms, a reference is just an alias to the referenced object.简单来说,引用只是被引用的 object 的别名。 When a reference is const it means you may not modify the object via that reference (the object can be modified via other means, this distinction is important, especially with multithreading).当引用为const时,意味着您不能通过该引用修改 object(object 可以通过其他方式修改,这种区别很重要,尤其是多线程)。 Copying a const reference is like copying the referenced object:复制const引用就像复制引用的 object:

 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 and z will both hold the string "bar" , though x is not modified in the last two lines. yz都将保存字符串"bar" ,尽管x在最后两行中没有修改。 And if TCPConnPtr has no weird copy constructor then thats basically also what happens in your code (if it does try to modify socket you would get a compiler error).如果TCPConnPtr没有奇怪的复制构造函数,那么这基本上也是你的代码中发生的事情(如果它确实尝试修改socket ,你会得到一个编译器错误)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM