我应该使用noexcept getter总是? [英] Should I use noexcept for getters always?

查看:77
本文介绍了我应该使用noexcept getter总是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该在C ++ 11中为getter使用noexcept方法修饰符吗?

Should I use noexcept method modifier for getters always in C++11?

我的意思是简单的getter在这里只返回成员。
至少在我所有的getters我有一个异常不可能
抛出。一个缺点是,一个getter得太冗长:

I mean simple getters here that just return members. At least in all my getters I have here an exception can't possibly be thrown. One downside is that a getter gets too verbose:

const std::string& getName() const noexcept{ return name; }

在Stroustrup的书中指出的好处是编译器
可能做一些

The good side as pointed out in Stroustrup's book is that the compiler might do some optimizations here and there.

推荐答案

noexcept 难以收回。例如,稍后可以做一些简单的更改返回类型为 std :: string (无论什么原因),但是因为需要分配字符串的副本,它可以抛出。

noexcept is a promise that is very hard to take back. For example, you could later do something as simple as change the return type to std::string (for whatever reason), but because that needs to allocate a copy of the string, it can throw.

因此,标准只是在需要或非常有益时才添加 noexcept ,我认为这是一个很好的规则。你需要问自己的问题是,这个方法的调用者需要它不抛出吗?

So the standard went the way of "add noexcept only when it's necessary or highly beneficial", and I think that's a good rule to follow. The question you need to ask yourself is, will the callers of this method need it to not throw?

这篇关于我应该使用noexcept getter总是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆