正确设置外部指针分配内存在c++中
Proper set external pointer for allocate memory in C++
如何在c++中正确使用外部指针来分配构造函数中的内存和释放析构函数中的内存?下面是一个不能正常工作的代码示例。请考虑一下。
#include <iostream>
using namespace std;
class Foo
{
public:
Foo() : str(nullptr)
{
str = new string();
}
~Foo()
{
if (str != nullptr)
{
delete str;
str = nullptr;
}
}
void getString(string ** pStr)
{
*pStr = str;
}
private:
string * str;
};
int main()
{
string * mainStr = nullptr;
Foo().getString(&mainStr);
if (mainStr == nullptr)
cout << "is null";
else
cout << "is not null";
return 0;
}
如何写上面的代码,以使mainStr
变量有正确的值(nullptr
在这种情况下)?
在c++中,你需要一个对象的实例来使用它的非static
成员函数。
在你的例子中:
int main(void)
{
Foo my_foo;
std::string * p_string = nullptr;
my_foo.getString(&p_string);
if (mainStr == nullptr)
cout << "is null";
else
cout << "is not null";
return 0;
}
您将需要在getString
中测试pStr
是否为null,因为分配给空指针是未定义的行为。
相关文章:
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 为什么以下C++代码中存在内存泄漏?
- 以下代码是否存在内存泄漏?
- 放置 新 在共享内存中已存在的对象上
- 假设传递给 OpenGL 的结构数组的内存布局存在潜在错误
- 如果操作系统未清除内存泄漏,则在程序完成后内存泄漏是否仍然存在?
- 存在内存访问异常,但我不确定我的代码中出了什么问题
- gpc服务器不会释放内存,是否存在内存泄漏?
- 是否有可能存在不会崩溃程序的内存问题
- 存在内存泄漏问题的链接列表
- 我可以检查共享内存中是否存在地址
- QT图像查看器示例,可能存在内存泄漏
- 线程:join上是否存在具有synchronized with relationship的隐式内存障碍
- 为什么堆栈中的函数局部变量之间存在内存空间
- C :当居民记忆缓慢增加时,是否存在内存泄漏
- 是否存在内存泄漏,如果是,为什么?
- 如果函数返回 std::vector<std::string>,是否存在内存泄漏?
- 如何追捕瓦尔格林德说不存在的内存泄漏?
- purify中存在错误的内存泄漏
- 检测到指针引用可能存在内存泄漏