首页 > 解决方案 > 在 C++ 中将 int 作为 bool 参数传递

问题描述

有人可以解释这段代码中发生了什么:

这里的例子: https ://ideone.com/1cFb4N

#include <iostream>

using namespace std;

class toto
{
public:
    bool b;
    toto(bool x)
    {
        cout<< "constructor bool:" << (x ? "true": "false")<<endl;
        b = x;
    }
    ~toto() {}
};

int main()
{
    toto t = new toto(0);
    cout << "t.b is " << (t.b ? "true": "false")<<endl;
    t = new toto(false);
    cout << "t.b is " << (t.b ? "true": "false")<<endl;
    return 0;
}

输出:

constructor bool:false
constructor bool:true
t.b is true
constructor bool:false
constructor bool:true
t.b is true

标签: c++pointersconstructorbooleanimplicit-conversion

解决方案


在这份声明中

toto t = new toto(0);

t类类型的对象toto由表达式返回的指针初始化new toto(0)。由于返回的指针不等于nullptrthen 它被隐式转换为布尔值 true。

所以事实上你有

toto t = true;

除了由于分配对象的地址丢失而导致内存泄漏。所以分配的对象不能被删除。

您可以通过以下方式想象上面的声明。

toto *ptr = new toto(0)
toto t = ptr;

所以这个输出的第一行

constructor bool:false
constructor bool:true

对应于参数为 0 的动态创建的对象

new toto(0)

然后返回的指针用作初始化器,并隐式转换true为用于初始化声明对象的布尔值t。所以第二行显示了值为 true 的转换构造函数(带参数的构造函数)的调用。

上面的声明和这个赋值语句没有太大区别

t = new toto(false);

因为在赋值的右手边又使用了一个指针。

因此隐式定义的复制赋值运算符将不等于的指针值转换为nullptr布尔值true

这个作业你可以想象如下方式

toto *ptr = new toto(false);
t = toto( ptr );

再次出现内存泄漏。

来自 C++ 14 标准(4.12 布尔转换)

1 算术、无范围枚举、指针或指向成员类型的指针的纯右值可以转换为 bool 类型的纯右值。将零值、空指针值或空成员指针值转换为 false;任何其他值都将转换为 true。对于直接初始化 (8.5),std::nullptr_t 类型的纯右值可以转换为 bool 类型的纯右值;结果值为假。


推荐阅读