什么是getter(按值)方法的异常安全保证?
What is the exception safety guarantee for getter (by value) methods?
对于下面的示例类,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_alloc
。getB()
、getD()
、getE()
同上
我认为你所有的操作都满足强异常安全,前提是(在相关的地方)Bar(const Bar&)
复制构造函数是强安全的。此外,getA
将满足无抛出保证,前提是a
被初始化,例如在构造函数中。
这些const
方法没有修改Foo
的任何部分,因此主要关注的是新创建的vector
s的泄漏-如果在将c
或e
的成员复制到返回值时出现异常,这些应该被自动释放。
必须正确初始化a
的原因是,复制未初始化的数据可能会对诸如Itanium之类的架构产生影响,如Bathsheba的回答所述。
相关文章:
- C++代码中的异常安全
- 编写"anti-lack of memory"异常安全代码
- std:string::substr 异常安全吗?
- 如何以异常安全的方式使用放置新?
- 通过引用从 c++ 函数异常返回对象是否安全
- 异常安全服务器
- 实现 std::vector::p ush_back 强异常安全
- 标准::unique_ptr和异常安全
- 如何使用QThreads使无锁生产者-消费者线程交换更加异常安全
- 使功能异常安全
- 与构造函数参数相关的异常安全的习语
- uninitialized_copy() 异常安全吗?
- 为什么我们需要 RAII 来解决异常安全问题
- 异常安全构造函数
- 关于 swap() 操作的异常安全 - 这有什么问题?
- std::vector::擦除异常安全
- 异常安全 - 用于可靠回滚对象状态的模式
- 异常安全的 for 循环
- 异常安全代码和移动语义
- 向量::插入的异常安全保证是什么?