getter(按值)方法的异常安全保证是什么?
What is the exception safety guarantee for getter (by value) methods?
对于以下示例 class,getter 方法的 exception safety 保证是什么?
这样的 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_alloc
。同上 getB()
、getD()
和 getE()
.
我认为你的所有操作都满足强异常安全,前提是(相关的)Bar(const Bar&)
复制构造函数是强安全的。此外,getA
将满足 nothrow 保证,前提是 a
已初始化,例如在构造函数中。
Foo
的任何部分都没有被这些 const
方法修改,所以主要关注的是新创建的 vector
s 的泄漏 - 如果有一个将成员从 c
或 e
复制到 return 值时出现异常。
a
必须正确初始化的原因是复制未初始化的数据可能会引发安腾等架构,如 Bathsheba's answer 中所述。
对于以下示例 class,getter 方法的 exception safety 保证是什么?
这样的 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_alloc
。同上 getB()
、getD()
和 getE()
.
我认为你的所有操作都满足强异常安全,前提是(相关的)Bar(const Bar&)
复制构造函数是强安全的。此外,getA
将满足 nothrow 保证,前提是 a
已初始化,例如在构造函数中。
Foo
的任何部分都没有被这些 const
方法修改,所以主要关注的是新创建的 vector
s 的泄漏 - 如果有一个将成员从 c
或 e
复制到 return 值时出现异常。
a
必须正确初始化的原因是复制未初始化的数据可能会引发安腾等架构,如 Bathsheba's answer 中所述。