我有以下问题。我创建了一个类,并将指向该类的指针存储在另一个类中。创建后,一切正常。然而,一步之后,类似乎消失了。
我在这里写了一个非常简单的测试场景:
#include <iostream>
using namespace std;
class test
{
public:
test();
bool ok;
};
test::test()
{
ok = false;
}
class func
{
public:
func();
void check();
test *pTest;
};
func::func()
{
test temptest = test();
cout << temptest.ok << endl;
pTest = &temptest;
cout << pTest->ok << endl;
}
void func::check()
{
cout << pTest->ok << endl;
};
int main( int argc, char *argv[] )
{
func mFunc = func();
// what happens here
mFunc.check();
}
以上程序输出如下:
0
0
204
从 204 开始,我猜测我之前创建的类不知何故已经消失了。
你能告诉我发生了什么以及为什么吗?
最佳答案
问题是您正在创建一个范围“有限”的对象。
func::func()
{
test temptest = test(); // temptest construction
cout << temptest.ok << endl;
pTest = &temptest;
cout << pTest->ok << endl;
} // temptest descrution
在构建 func 之后,pTest 现在引用了一个无效的对象。
你必须使用动态内存或共享指针来管理指针。
#include <iostream>
using namespace std;
class test
{
public:
test();
bool ok;
};
test::test()
{
ok = false;
}
class func
{
public:
func();
~func();
void check();
test *pTest;
};
func::func()
{
pTest = new Test();
cout << pTest->ok << endl;
cout << pTest->ok << endl;
}
func::~func() { delete pTest; }
void func::check()
{
cout << pTest->ok << endl;
};
int main( int argc, char *argv[] )
{
func mFunc = func();
// what happens here
mFunc.check();
}
现在 test 的构造函数分配一个新对象并存储该对象的地址,而析构函数可以释放内存。以这种方式管理内存不是一个好习惯。
使用共享指针代替 shared_ptr 或 unique_ptr,但这需要一些其他知识,例如移动语义。
关于c++ - 这个指针一旦创建会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13782657/