C++对象创建引起的奇怪分段错误
我通过启动类对象遇到了一个奇怪的问题。 这个问题既奇怪又不容易重现。不过我会尝试举一个有代表性的例子。 我有继承类。
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) {
...
}
};
有时,如果我用以下方式启动对象,我会通过初始化得到分段错误错误。
FooClass foo1;
foo1.doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
如果我使用显式指针 new,那么就可以了。
FooClass *foo1= new FooClass();
foo1->doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
以下代码将在第 2 行给我一个编译器错误
FooClass foo1();
foo1.doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
。我应该如何正确启动一个对象,特别是当它具有默认构造函数和带有参数的构造函数时。
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();
If I use explicit pointer new, then it is OK..
FooClass *foo1= new FooClass();
foo1->doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,您的最后一个问题...
不会创建 FooClass 类型的对象,而是声明一个名为 foo1() 的函数,该函数不带任何参数并返回 FooClass。删除括号以创建实例,就像在第一个代码示例中所做的那样。
为什么出现分段错误可能与我们看不到的析构函数有关,并且在第二个泄漏的示例中不会调用它。
Your last issue first...
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.
您的构造函数或
doSomething()
中可能存在一些错误。如果不知道这些函数中发生了什么,就无法说出该错误到底是什么。You probably have some bug in your constructor or in
doSomething()
. Without knowing what happens in these functions there is no way to say what exactly that bug is.很可能
sizeof(YourClass)
对于堆栈而言太大,这可以解释为什么只有堆分配成功。Most likely
sizeof(YourClass)
is too large for the stack, which would explain why only heap allocation succeeds.仅将
->
与指针一起使用。需要是
Only use
->
with pointers.Needs to be