本文介绍了转换功能的错误检查考虑不错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一种简单的方式来检查一个对象是否有效。我想到一个简单的转换函数,像这样:

I'd like to have a simple way of checking for an object to be valid. I thought of a simple conversion function, something like this:

operator bool() const { return is_valid; }

检查它是否有效现在很简单

Checking for it to be valid would be very simple now

// is my object invalid?
if (!my_object) std::cerr << "my_object isn't valid" << std::endl;

这被认为是一个好习惯吗?

Is this considered a good practise?

推荐答案

在C ++ 03中,您需要使用,以避免邪恶的事情:

In C++03, you need to use the safe bool idiom to avoid evil things:

int x = my_object; // this works

在C ++ 11中,您可以使用显式转换:

In C++11 you can use an explicit conversion:

explicit operator bool() const
{
    // verify if valid
    return is_valid;
}

这样你需要明确的转换为bool,所以你可以不再是偶然的疯狂的事情(在C ++中,你可以随时做出有意义的疯狂的事情):

This way you need to be explicit about the conversion to bool, so you can no longer do crazy things by accident (in C++ you can always do crazy things on purpose):

int x = my_object; // does not compile because there's no explicit conversion
bool y = bool(my_object); // an explicit conversion does the trick

这样的地方,像如果 while 需要布尔表达式,因为这些语句的条件是上下文转换为/ / p>

This still works as normal in places like if and while that require a boolean expression, because the condition of those statements is contextually converted to bool:

// this uses the explicit conversion "implicitly"
if (my_object)
{
    ...
}

这被记录在§ 4 [conv]

This is documented in §4[conv]:

(有什么区别是使用 bool t(e); 而不是 bool t = e; 。)

(What makes the difference is the use of bool t(e); instead of bool t = e;.)

这个上下文转换为bool的地方是:

The places were this contextual conversion to bool happens are:


  • 条件 if while 对于语句;

  • 逻辑否定的运算符,逻辑连接 &< / code>和逻辑分离 || ;

  • 条件运算符?:;

  • 条件 static_assert ;

  • noexcept 异常说明符的可选常量表达式

  • the conditions of if, while, and for statements;
  • the operators of logical negation !, logical conjunction &&, and logical disjunction ||;
  • the conditional operator ?:;
  • the condition of static_assert;
  • the optional constant expression of the noexcept exception specifier;

这篇关于转换功能的错误检查考虑不错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 07:59