好的或坏的做法,使纯虚函数noexcept

时间:2016-04-15 10:58:37

标签: c++ c++11

制作纯虚函数noexcept是好还是坏?我一直认为我们不应该对它的实现类施加额外的限制,因为它实现应该没有抛出,因为这可能导致实现中的修改和不必要的try catch块以防止异常转移。我认为实现应该决定函数是否可以标记为no而不是异常规范应该决定实现?

如果我在这里错了,请有人纠正我吗?

2 个答案:

答案 0 :(得分:8)

noexcept isn't about implementations, it's about interface. Is the abstract operation represented by the virtual function one that fundamentally cannot fail? Then make the virtual function noexcept. If the operation could fail theoretically, even if none of the implementations you write can't, don't.

答案 1 :(得分:7)

noexcept is part of member function specification, in the same way as its return type, parameter list, and const qualifier. It is there to help users of the function - obviously, at the expense of function's implementers.

If you need to give implementers more flexibility while providing your users with a noexcept function, make a pair of functions - a non-virtual public function with noexcept, and a protected virtual function without noexcept. Make the public noexcept function call virtual implementation, and handle exceptions to hide them from its callers:

class Base {
protected:
    virtual void doSomethingImpl() = 0;
public:
    void doSomething() noexcept {
        try {
            doSomethingImpl();
        } catch(...) {
            // Provide some handling here
        }
    }
};

class Derived : public Base {
    void doSomethingImpl() {
        ... // Implementers have flexibility to throw here
    }
}