使用new并传递指针时的基本C ++段错误

时间:2016-01-27 22:20:41

标签: c++

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

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,则测试_-> class_function()可以正常工作。当我在类构造函数之外使用new并尝试通过函数传递指针时,它似乎只是段错误

1 个答案:

答案 0 :(得分:3)

当您在init_some class()写信时:

tmp = new some_class(variables,variables);

实际上,您将新指针存储在按值传递的参数中。但是这个参数是函数的局部参数,一旦函数返回就会丢失。

因此,如果您在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_成员。那你就不再需要参数了。