【问题标题】:Implicit conversion of return expressions to bool返回表达式到布尔值的隐式转换
【发布时间】:2017-06-20 06:40:19
【问题描述】:

在尝试构建一些遗留代码(使用最新版本的 boost)时,我偶然发现了以下问题:

#include <boost/scoped_array.hpp>

bool foo(const boost::scoped_array<int> bar) {
    return bar;
}

bool foo2(const boost::scoped_array<int> bar) {
    const bool r = bar;
    return r;
}

bool foo3(const boost::scoped_array<int> bar) {
    return bar ? true : false;
}

上面的源码不会编译。 foofoo2 都是错误的。准确地说,不允许预期的从 scoped_array 到 bool 的隐式转换:

➜  /tmp clang++ --std=c++14 testconversion.cpp -o testconversion.o
testconversion.cpp:4:12: error: no viable conversion from returned value of type 'const boost::scoped_array<int>' to function return type 'bool'
    return bar;
           ^~~
testconversion.cpp:8:16: error: no viable conversion from 'const boost::scoped_array<int>' to 'const bool'
    const bool r = bar;

这带来了两个问题:

  1. 为什么 foo 和 foo2 无效? reference 明确提到:

    在初始化 T2 类型的新对象时,包括返回 返回 T2 的函数中的语句;

  2. 什么时候合法。遗留代码肯定用于使用 boost 1.48.0 构建。有没有
    1. boost 库的变化
    2. 更改语言/编译器

【问题讨论】:

  • 所以编译器说'错误'?
  • 更多的话。
  • 你不想打扰我们吗?
  • 查看我所做的编辑

标签: c++ boost implicit-conversion


【解决方案1】:

查看boost::scoped_array的文档:

operator unspecified-bool-type () const; // never throws

返回一个未指定的值,当在布尔上下文中使用时,它等效于get() != 0

您必须使用static_cast 将您的boost::scoped_array 转换为bool

bool foo(const boost::scoped_array<int>& bar) {
    return static_cast<bool>(bar);
}

bool foo2(const boost::scoped_array<int>& bar) {
    const bool r = static_cast<bool>(bar);
    return r;
}

也许只是一个错字,但在您的示例中,您按值传递了 boost::scoped_array。它没有复制构造函数,所以按值传递也会导致错误。


它适用于 Boost 1.48.0,因为该版本中的 operator_bool.hpp 不同。在 Boost 1.64.0 中,same header 包含 explicit operator bool () const;,这会阻止您在使用 -std=c++14(或 -std=c++11)编译 boost::scoped_array 实例时复制初始化 bool。如果您使用 -std=c++98 编译代码,您的代码也可以与 Boost 1.64.0 一起使用。

【讨论】:

  • 感谢您找到根本原因。这很有帮助。
  • 特别是,错误代码假定连续两次隐式转换(到unspecified-bool-type,然后到bool)。这是不允许的。使第二次转换显式解决它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-05
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
相关资源
最近更新 更多