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

标签 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,那么 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/

相关文章:

c++ - 定义缓冲区大小正确 "Stack around the variable String was corrupted"

c++ - C2440 重载函数 MsgProc

c++ - 返回一个新对象和另一个值

c++ - c++强制使用指针的场景

c++ - 更改组合框选择的 DateTimePicker 样式失败

c++ - 使用 nlohmann json 包从 json 转换时出错

c++ - 在 C++ 类中使用位域的未对齐属性

c++ - 无法将 uint8_t vector 迭代器转换为 const uint8_t *

c++ - 当我们对一个int进行运算时,结果是不是暂存在一个int中呢?

c++ - 在C++中创建线程时出错