我可以依赖布尔表达式中的逗号运算符吗
Can I rely on the comma operator in a bool expression
void test()
{
string s = " ,";
if (boost::trim_if(s, boost::is_any_of(" ,")), s.empty())
{
cout << "empty";
}
else
{
cout << s << endl;
}
}
根据此 How does the Comma Operator work,表达式应该等于 boost::trim_if(),其中 returns 无效。
但它现在可以工作了,所以它执行 boost::trim_if() 和 s.empty()。
我可以依靠这种表达方式吗?
你也许会说我应该这样写代码:
boost::trim_if(s, boost::is_any_of(" ,"));
if (s.empty())
{
cout << "empty";
}
但我的情况是我们的旧代码是
string s;
if(FAILED(GetStringFromAPI(s)) || s.empty() )
{
}
我只想修改一行
if(FAILED(GetStringFromAPI(s)) || (boost::trim_if(...), s.empty()) )
{
}
是的,这完全可以使用。 cppreference says this(强调我的):
In a comma expression E1, E2
, the expression E1
is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2
begins
请注意,与其他运算符一样,逗号运算符可以被覆盖,在这种情况下,上述情况可能不成立。
void test()
{
string s = " ,";
if (boost::trim_if(s, boost::is_any_of(" ,")), s.empty())
{
cout << "empty";
}
else
{
cout << s << endl;
}
}
根据此 How does the Comma Operator work,表达式应该等于 boost::trim_if(),其中 returns 无效。 但它现在可以工作了,所以它执行 boost::trim_if() 和 s.empty()。 我可以依靠这种表达方式吗?
你也许会说我应该这样写代码:
boost::trim_if(s, boost::is_any_of(" ,"));
if (s.empty())
{
cout << "empty";
}
但我的情况是我们的旧代码是
string s;
if(FAILED(GetStringFromAPI(s)) || s.empty() )
{
}
我只想修改一行
if(FAILED(GetStringFromAPI(s)) || (boost::trim_if(...), s.empty()) )
{
}
是的,这完全可以使用。 cppreference says this(强调我的):
In a comma expression
E1, E2
, the expressionE1
is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expressionE2
begins
请注意,与其他运算符一样,逗号运算符可以被覆盖,在这种情况下,上述情况可能不成立。