正确设置外部指针分配内存在c++中

Proper set external pointer for allocate memory in C++

本文关键字:内存 存在 c++ 分配 指针 设置 外部      更新时间:2023-10-16

如何在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,因为分配给空指针是未定义的行为。