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