C ++通过对象创建的奇怪分段错误 [英] C++ strange segmentation fault by object creation
问题描述
我有一个奇怪的问题,通过启动一个类对象。
问题是奇怪,但不容易重现。但我会尝试给一个指示的例子。
我有继承类。
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,那么它是OK ..
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.
解决方案
推荐答案
c $ c> FooClass foo1();
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.
为什么你得到一个segmmentation错误可能与你的析构函数,我们看不到,这不会被调用你的第二个例子泄漏。
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 ++通过对象创建的奇怪分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!