基本C++段错误,当使用new和传递指针时

Basic C++ segfault when using new and passing a pointer

本文关键字:new 指针 段错误 C++ 错误 基本      更新时间:2023-10-16

有人可以在这里解释一下段错误吗:

class foo
{
  private:
    some_class *test_;

    void init_some_class(some_class*);
    void use_class();
 }
 foo::foo()
 {
     //test_ = new some_class(variables, variables); //THIS WOULD WORK
 }
 void foo::init_some_class(some_class *tmp)
 {
   tmp = new some_class(variables,variables);
 }
 void foo::use_class()
 {
   test_->class_function() //THIS SEGfaults
 }

我会通过 init_some_class(test_) 调用该功能; 如果我在构造函数中使用new,那么test_->class_function()可以正常工作。 当我在类构造函数之外使用 new 并尝试通过函数传递指针时,它似乎只会出现段错误

当你用init_some class()

tmp = new some_class(variables,variables);

实际上,您将新指针存储在按 Value 传递的参数中。 但是此参数是函数的本地参数,一旦函数返回就会丢失。

因此,如果您在某处调用init_some class(test_) test_的值将转移到tmp,但更改后的tmp仍然是函数的本地。 因此,你会得到一个段错误test_它仍然未初始化。

可能的解决方案:

所描述用例的简单解决方案可能是通过引用传递参数:

void foo::init_some_class(some_class *& tmp)  // note the &
{
   tmp = new some_class(variables,variables);
}

有了这个定义,当调用init_some class(test_)时,原始test_指针被修改。

另一种解决方案是让init_some_class()直接更改test_成员。 这样,您将不再需要参数。