简体   繁体   English

getter和setter的`noexcept`说明符

[英]`noexcept` specifier for getters and setters

Let's say I have the following code: 假设我有以下代码:

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;
}

Using noexcept for integral types and pointers seems for me pretty obvious. 对于整数类型和指针使用noexcept对我来说非常明显。

But what are recommendations in case of not integral types like classes and structures that do not throw exceptions in constructor/copy-constructor and constructors of their parts explicitly (meaning using throw in constructor body)? 但是,如果不是类和结构之类的整数类型的建议是什么,不会在构造函数/复制构造函数和它们的部分的构造函数中明确地抛出异常(意味着使用构造函数体中的throw )?

You should avoid noexcept specifiers for functions which may throw (unless you're prepared to have your code call std::terminate() ). 对于可能抛出的函数,你应该避免使用noexcept说明符(除非你准备让你的代码调用std::terminate() )。 Explicit throw specifiers are deprecated, so don't rely on them, rather use the noexcept operator . 不推荐使用显式throw说明符,因此不要依赖它们,而应使用noexcept运算符 For example 例如

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

Outside of special member functions, noexcept is not that useful. 在特殊成员函数之外, noexcept没有那么有用。 But if you want it: 但如果你想要它:

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

First way for getter: 吸气剂的第一种方式:

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

Second way is for setter: 第二种方式是针对二传手:

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

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

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