如何使用正确的外部指针在构造函数中分配内存并在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
)?
答案 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,因为分配空指针是未定义的行为。