我想知道这个函数声明中的逻辑:
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/