返回 private dynamic int 的值导致段错误

returning the value of private dynamic int results in seg fault

我正在做一个快速测试,看看如何将动态分配的私有数据成员的值获取到 class 之外的另一个动态分配的变量,但我无法返回它们的值。每当我尝试时,都会在运行时导致分段错误。我一直在慢慢简化代码,甚至简化为 int 数据类型,我无法让它工作。这是代码:

#include <iostream>
class testing{
    public:
        testing();
        int getValue();
    private:
        int* asdf;
};
int main(){
    int* test = NULL;
    int test2, test3;
    testing test1;

    test2 = test1.getValue();
    test  = new int(test2);
    test3 = *test;

    std::cout << test3 << std::endl;

    return 0;
}
testing::testing(){
    int* asdf = new int(3);
}
int testing::getValue(){
    return *asdf;
}

我希望代码只打印出 3,但事实并非如此。我搞砸了什么?

这里存在空指针引用问题。分配一些内存并初始化 test 或使 test 指向其他一些 int.

编辑:正如@songyuanyao 所指出的,构造函数没有初始化原始testing::asdf,而是初始化了新的局部变量asdf。您还应该删除 int* 说明符以避免该问题。

int main(){
    int* test = NULL;    //null pointer. You did not give any valid address.
    int test2, test3;
    testing test1;

    test2 = test1.getValue();
    test  = new int(test2);
    test3 = *test;       //ERROR! Trying to dereference the null pointer

    std::cout << test3 << std::endl;

    return 0;
}
testing::testing(){
    asdf = new int(3);  // removed int*, as original expression does hide your member variable.
}

另外,裸new表达式容易产生内存泄漏问题。我建议你熟悉C++中的智能指针。