有人可以解释这里的段错误吗:
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);
您实际上是将新指针存储在按值传递的参数中。但是这个参数是函数的局部参数,一旦函数返回就会丢失。
所以如果你在某处调用 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_
成员。然后您将不再需要参数。
关于c++ - 使用 new 和传递指针时的基本 C++ 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35049219/