c++ - 在 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
解决方案
在这份声明中
toto t = new toto(0);
t
类类型的对象toto
由表达式返回的指针初始化new toto(0)
。由于返回的指针不等于nullptr
then 它被隐式转换为布尔值 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 类型的纯右值;结果值为假。
推荐阅读
- ios - 如果已安装 Apps-flyer 的一个链接,则无法打开应用程序?
- sass - 如何在 scss 中使用 mixin 更改全局 scss 变量的值?
- ios - 确定表格视图单元格中的图像是否完全可见
- python - 变量分配如何在函数中工作?
- android - 如何在灵活的应用内更新中弹出自定义对话框?
- autodesk-forge - 如何在没有 ngrok 的情况下使用 Forge Design Automation?
- return - 如何使用 Easy Mock 为方法返回接口方法编写断言?
- sql - Powerpivot 数据连接不会保存密码
- python - 无法使用 npm 安装 bcrypt
- amazon-web-services - 从 aws cognito 中的用户池中导出用户