基本C++段错误,当使用new和传递指针时
Basic C++ segfault when using new and passing a pointer
有人可以在这里解释一下段错误吗:
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_
成员。 这样,您将不再需要参数。
相关文章:
- 在将 new 与指针一起使用时,创建数组的指定长度
- 在C++中,如果我可以直接将整数分配给指针而不使用"new",为什么要使用"new"?
- 传递给放置 new 的指针是否是指向其对象表示形式的非 UB 指针?
- 删除使用 new 创建的 2D 或 3D 指针
- 基类指针:在哪里使用 new 和 delete
- 双指针在使用 new 时不调用对象构造函数
- 'new'和'='与指针的区别
- 哪些资源是由智能指针管理的,而它们的内存不是由new分配的
- (C++)如何在不导致 mem 泄漏的情况下将指针传递到分配了'new'的函数?
- C++:为什么可以在没有事先使用 new 的情况下在指向结构的指针上使用 delete?
- 为什么运算符"new"需要指针才能工作?
- 将指针返回使用New创建的数组数组
- "new"不会将内存分配给作为类的数据成员的指针
- 带"new"的指针和带"&variable"的指针有什么区别
- 基于索引的 alloca 返回的指针访问和"placement new"的效果
- 将内存分配给 2D 数组时,“new int*[rowCount];”的含义是什么?是 2D 数组,是指向数组的指针数组
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 使用 malloc 而不是 new 会导致 free():指针错误无效
- 如何将一系列指针分配给Usinig New
- 如何将`new`用于数组的指针