正确设置外部指针,用于在C ++中分配内存

时间:2014-03-19 18:54:27

标签: c++ pointers

如何使用正确的外部指针在构造函数中分配内存并在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)?

1 个答案:

答案 0 :(得分:1)

在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;
}

您需要在pStr中测试getString为null,因为分配空指针是未定义的行为。