C++ strange segmentation fault by object creation(对象创建引起的 C++ 奇怪的分段错误)
问题描述
通过启动类对象,我遇到了一个奇怪的问题.这个问题很奇怪,也不容易重现.但是,我将尝试举一个说明性的例子.我有继承类.
I have a strange problem by initiating a class object. The problem is as strange as well not easily reproducible. However I will try to give an indicating example. I have inheritance classes.
class BarClass {
public:
BarClass() {
...
}
BarClass(int i, int j) {
...
}
void doSomething() { ... }
};
class FooClass : public BarClass {
public:
FooClass() {
}
FooClass(int i, int j) : BarClass(i,j) {
...
}
};
有时如果我用以下方式启动对象,我会通过初始化得到分段错误错误.
Sometime if I initiate objects with following manner, I will get segmentation fault error by initialization.
FooClass foo1;
foo1.doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
如果我使用显式指针new,那么没关系..
If I use explicit pointer new, then it is OK..
FooClass *foo1= new FooClass();
foo1->doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
以下代码将在第 2 行给我一个编译器错误.
The following code will give me a compiler error on line 2.
FooClass foo1();
foo1.doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
我应该如何正确地初始化一个对象,尤其是当它有默认构造函数和带有参数的时候.
how should I properly initiate a object, especially when it has default constructor and those with arguments.
推荐答案
你的上一期先...
FooClass foo1();
不会创建 FooClass 类型的对象,而是声明一个名为 foo1() 的函数,该函数不接受任何参数并返回一个 FooClass.删除括号以创建实例,就像您在第一个代码示例中所做的那样.
does not create an object of type FooClass but declares a function called foo1() that takes no parameters and returns a FooClass. Remove the parentheses to create the instance as you did in the first code sample.
为什么你得到一个分段错误可能与你的析构函数有关,我们看不到,这在你的第二个泄漏示例中没有被调用.
why you get a segmmentation fault may have something to do with your destructor which we can't see, and this doesn't get invoked in your second example which leaks.
这篇关于对象创建引起的 C++ 奇怪的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对象创建引起的 C++ 奇怪的分段错误


基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01