相关疑难解决方法(0)

为什么要将异常作为引用引用到const?

我已经多次听过和读过,最好将异常作为引用而不是引用来引用.为什么是

try {
    // stuff
} catch (const std::exception& e) {
    // stuff
}
Run Code Online (Sandbox Code Playgroud)

比...更好

try {
    // stuff
} catch (std::exception& e) {
    // stuff
}
Run Code Online (Sandbox Code Playgroud)

c++ const exception

74
推荐指数
3
解决办法
2万
查看次数

当const引用生命周期是当前范围的长度时,为什么使用const非引用

因此,在c ++中,如果将函数的返回值赋给const引用,则该返回值的生存期将是该引用的范围.例如

MyClass GetMyClass()
{
    return MyClass("some constructor");
}

void OtherFunction()
{
    const MyClass& myClass = GetMyClass(); // lifetime of return value is until the end            
                                           // of scope due to magic const reference
    doStuff(myClass);
    doMoreStuff(myClass);
}//myClass is destructed
Run Code Online (Sandbox Code Playgroud)

因此,无论您通常将函数的返回值分配给const对象,您都可以将其分配给const引用.在函数中是否有一种情况,您不希望在赋值中使用引用而是使用对象?你为什么要写这行:

const MyClass myClass = GetMyClass();
Run Code Online (Sandbox Code Playgroud)

编辑:我的问题困扰了几个人,所以我添加了GetMyClass函数的定义

编辑2:如果你没有读过这个问题,请不要尝试回答这个问题:http: //herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-常量/

c++

6
推荐指数
1
解决办法
527
查看次数

标签 统计

c++ ×2

const ×1

exception ×1