通过函数传递后,我该如何降低指针
How can I downcast a pointer after passing it through a function?
我创建了一个函数,该函数将基本指针返回到func中创建的派生对象。似乎它不起作用!好像派生数据丢失了,指针指向基本对象...
有类请求,这是基类,并且有class loginrequest-派生请求。为了检查对象的类型,我打印了对象的名称(typeId(*r(.name(((。在Func((内部,打印输出被证明为" LoginRequest",这很好,因为这是尖的对象。(查看代码(但是在返回该指针后,当我再次打印它是类型的时候,事实证明它是"请求"。你们能帮我吗?为什么返回的指针丢失了派生数据?
Request * r = new Request();
r = func(); // r is now supposed to point the LoginRequest object.
std::cout<< typeid(*r).name() <<std::endl; //print the type of OBJECT
//func
Request * func()
{
Request * r;
LoginRequest l = LoginRequest();
r = &l;
std::cout<< typeid(*r).name() <<std::endl; //print the type of OBJECT
return r;
}
您正在返回一个具有自动存储持续时间的对象l
的指针。
删除返回的指针具有不确定的行为。
您需要使用new
动态创建该对象,并删除函数外部滥用new
引起的内存泄漏:
Request* func()
{
Request* r = new LoginRequest();
std::cout<< typeid(*r).name() <<std::endl; //print the type of OBJECT
return r;
}
// ...
Request * r = func();
std::cout << typeid(*r).name() << std::endl; //print the type of OBJECT
您正在创建本地LoginRequest
对象:
LoginRequest l = LoginRequest();
接受该地址:
r = &l;
返回:
return r;
但是l
在下一行上不超出范围:
}
您想在堆上创建它:
Request * func()
{
Request * r;
LoginRequest* l = new LoginRequest();
r = l;
std::cout<< typeid(*r).name() <<std::endl; //print the type of OBJECT
return r;
}
还使用智能指针而不是原始指针。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- 在C++中释放内存期间,迭代器与指针有何不同
- 通过函数传递后,我该如何降低指针
- 我如何用智能指针动态升起和降低
- (指针)降低测试分数后计算平均功能的问题
- 指向成员函数的指针与指向数据成员的指针有何不同
- 对齐方式与指针中尾随零的数量有何关系
- 使用“ static_cast”在空指针(单个或多个继承)上进行降低
- C++03 12.4/12对通过指针显式调用基类析构函数有何说明
- 为什么以及在何处在C++中使用引用和指针
- 使用带有TBB的函数指针会降低性能
- 如果 x 是一个指针,&x 与 x 有何不同?
- Fortran 中的指针与 C/C++ 指针究竟有何不同