c++ - 这个指针一旦创建会发生什么?

标签 c++ oop object

我有以下问题。我创建了一个类,并将指向该类的指针存储在另一个类中。创建后,一切正常。然而,一步之后,类似乎消失了。

我在这里写了一个非常简单的测试场景:

#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/

相关文章:

c++ - 模板化友元声明在 g++ 5.4.0 下不起作用——编译器错误或错误代码?

c++ - "POR"在嵌入式开发中是什么意思?

c++ - std::string 在参数中构造

java - 对象数组的初学者混淆

excel - 如何在vba引用库中查找函数

c++ - 什么是 C++ 中的容器或嵌套?

c++ - 在 Eigen C++ 中广播(两个) vector

python - python 2.7 中的 __add__ 矩阵方法

php - 类变量的作用域解析运算符

C++ 全局对象声明