c++ - 在 C++ 中将 int 作为 bool 参数传递

标签 c++ pointers constructor boolean implicit-conversion

有人可以解释一下这段代码中发生了什么:
例如: 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

最佳答案

在本声明中

toto t = new toto(0);
对象t类类型 toto由表达式 new toto(0) 返回的指针初始化.由于返回的指针不等于 nullptr然后它被隐式转换为 boolean 值 true。
所以实际上你有
toto t = true;
除了由于分配对象的地址丢失而导致内存泄漏。所以分配的对象不能被删除。
您可以通过以下方式想象上面的声明。
toto *ptr = new toto(0)
toto t = ptr;
所以这个输出的第一行
constructor bool:false
constructor bool:true
对应于参数为 0 的动态创建的对象
new toto(0)
然后返回的指针用作初始化器并隐式转换为 boolean 值 true用于初始化声明的对象 t .因此,第二行显示了值为 true 的转换构造函数(带参数的构造函数)的调用。
上面的声明和这个赋值语句没有太大区别
t = new toto(false);
因为在赋值的右手边再次使用了一个指针。
所以隐式定义的复制赋值运算符转换了不等于nullptr的指针的值到 boolean 值 true .
这个作业你可以想象如下方式
toto *ptr = new toto(false);
t = toto( ptr );
再次出现内存泄漏。
来自 C++ 14 标准(4.12 boolean 转换)

1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

关于c++ - 在 C++ 中将 int 作为 bool 参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64252680/

相关文章:

c++ - 在 HardwareStore 类中找不到匹配的构造函数 (C++)

c++ - 如何使用可变消息抛出 std::exceptions?

delphi - 如何将指向类型的指针视为指向该类型数组的指针

java - 如何使用已经存在的构造函数?

c - 从现有结构数组中查找并返回指向结构的指针

c++ - 通过指针进行的内存复制有时会丢失数据

c++ - 定义类构造器

c++ - 使用 websocketpp 库连接到 C++ websocket 服务器

c++ - Qt 设置小部件的文本方向

c++ - 逐行读取文本文件并计算比较运算符