C++ 初学者 : what is the point of using a variable by reference if using "const"?

标签 c++ constants pass-by-reference

我想知道这个函数声明中的逻辑:

CMyException (const std::string & Libelle = std::string(),...

按引用使用变量有什么意义?通常,只要变量可能在内部被修改,您就会通过引用传递一个变量...因此,如果您使用关键字const,这意味着它永远不会被修改。

这是矛盾的。

谁能给我解释一下?

最佳答案

实际上引用是用来避免不必要的对象拷贝。

现在,要理解为什么使用 const,试试这个:

std::string & x= std::string(); //error

编译会报错。这是因为表达式 std::string() 创建了一个不能绑定(bind)到非常量引用的临时对象。但是,临时变量可以绑定(bind)到 const 引用,这就是为什么需要 const 的原因:

const std::string & x = std::string(); //ok

现在回到代码中的构造函数:

CMyException (const std::string & Libelle = std::string());

它为参数设置一个默认值。默认值是从临时对象创建的。因此,您需要 const(如果您使用 reference)。

使用 const 引用还有一个好处:如果你有这样的构造函数,那么你可以像这样引发异常:

throw CMyException("error"); 

它从字符串文字 "error" 中创建一个类型为 std::string 的临时对象,并且该临时对象绑定(bind)到 const引用。

关于C++ 初学者 : what is the point of using a variable by reference if using "const"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9257380/

相关文章:

c++ - 快速排序的实现,几乎可以工作但不能

c - 为什么这个结构是由参数发送的?

传递参数时未设置 Java 类的属性

c++ - 使用 const 变量可以避免别名问题吗

C++,传递给函数的fstream对象作为引用,const?

c++ - std::ifstream 初始值在未初始化时检查为真

c++ - 使用 boost 处理 COM 变体

c++ - constexpr 的运行时错误

c++ - 如何在 C++ header 中声明数组?

java - Java 5+ 中的静态字符串常量 VS 枚举