什么是getter(按值)方法的异常安全保证?

What is the exception safety guarantee for getter (by value) methods?

本文关键字:安全 异常 方法 getter 按值 什么      更新时间:2023-10-16

对于下面的示例类,getter方法的异常安全保证是什么?

这样的getter方法是否提供了最低限度的强保证?

按值返回基本类型是否总是提供无抛出保证?

class Foo
{
public:
    // TODO: Constructor
    // Getter methods
    int getA() const { return a; }
    std::string getB() const { return b; }
    std::vector<int> getC() const { return c; }
    Bar getD() const { return d; }
    std::vector<Bar> getE() const { return e; }
protected:
    int a;
    std::string b;
    std::vector<int> c;
    Bar d;
    std::vector<Bar> e;
}

根本不能保证异常安全。

例如,如果a没有初始化,getA()可能会抛出一个异常(或者做任何其他事情,因为行为是未定义的)。有些芯片(例如Itanium)在读取一元变量时确实会发出信号。

如果内存不足,

getC()可能会抛出std::bad_allocgetB()getD()getE()同上

我认为你所有的操作都满足强异常安全,前提是(在相关的地方)Bar(const Bar&)复制构造函数是强安全的。此外,getA将满足无抛出保证,前提是a被初始化,例如在构造函数中。

这些const方法没有修改Foo的任何部分,因此主要关注的是新创建的vector s的泄漏-如果在将ce的成员复制到返回值时出现异常,这些应该被自动释放。

必须正确初始化a的原因是,复制未初始化的数据可能会对诸如Itanium之类的架构产生影响,如Bathsheba的回答所述。