Oli*_*ons 4 c++ const pass-by-reference
我想知道这个函数声明中的逻辑:
CMyException (const std::string & Libelle = std::string(),...
Run Code Online (Sandbox Code Playgroud)
通过引用使用变量有什么意义?通常你可以在内部修改时通过引用传递一个变量...所以如果你使用关键字,const这意味着它永远不会被修改.
这是矛盾的.
愿有人向我解释一下吗?
实际上,引用用于避免不必要的对象副本.
现在,要了解使用的原因const,请尝试以下方法:
std::string & x= std::string(); //error
Run Code Online (Sandbox Code Playgroud)
它会给出编译错误.这是因为表达式std::string()创建了一个临时对象,该对象不能绑定到非const引用.但是,临时可以绑定const引用,这就是为什么const需要:
const std::string & x = std::string(); //ok
Run Code Online (Sandbox Code Playgroud)
现在回到代码中的构造函数:
CMyException (const std::string & Libelle = std::string());
Run Code Online (Sandbox Code Playgroud)
它为参数设置默认值.默认值是从临时对象创建的.因此你需要const(如果你使用参考).
使用const引用也有一个优点:如果你有这样的构造函数,那么你可以像这样引发异常:
throw CMyException("error");
Run Code Online (Sandbox Code Playgroud)
它std::string从字符串文字中创建一个类型的临时对象"error",并将该临时对象绑定到const引用.
| 归档时间: |
|
| 查看次数: |
234 次 |
| 最近记录: |