繁体   English   中英

getter和setter的`noexcept`说明符

[英]`noexcept` specifier for getters and setters

假设我有以下代码:

class A {
    public:
        void SetInteger(const int val) noexcept { integerMember = val; }
        void SetString(const std::string& val) { stringMember = val; }
        int GetInteger() const noexcept { return integerMember; }
        std::string GetString() const { return stringMember; }

    private:
        int integerMember;
        std::string stringMember;
}

对于整数类型和指针使用noexcept对我来说非常明显。

但是,如果不是类和结构之类的整数类型的建议是什么,不会在构造函数/复制构造函数和它们的部分的构造函数中明确地抛出异常(意味着使用构造函数体中的throw )?

对于可能抛出的函数,你应该避免使用noexcept说明符(除非你准备让你的代码调用std::terminate() )。 不推荐使用显式throw说明符,因此不要依赖它们,而应使用noexcept运算符 例如

template<typename T>
class Foo
{
  T m_datum;
public:
  Foo& SetDatum(T const&x) noexcept(noexcept(m_datum=x))
  {
    m_datum = x;
    return *this;
  }
};

在特殊成员函数之外, noexcept没有那么有用。 但如果你想要它:

void SetString(const std::string& val) 
         noexcept(std::is_nothrow_copy_assignable<std::string>::value) {
}

吸气剂的第一种方式:

const std::string& GetString() const noexcept {return stringMember; }

第二种方式是针对二传手:

void SetString(std::string&& val) noexcept {
    swap(stringMember, val);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM