简体   繁体   English

具有指针变量的C ++分段故障类

[英]C++ segmentation fault class with pointer variable

[Edited post, based on previous answers and comments. [根据以前的答案和评论,编辑过的帖子。 I have tried several strategies, none of which have worked.] 我尝试了几种策略,但都没有奏效。]

I have a class D, with a member variable of class type E. E has two subclasses, E1 and E2. 我有一个类D,其成员变量的类类型为E。E有两个子类E1和E2。 When I try the following code, I get a segmentation fault (see detailed output below). 当我尝试以下代码时,我遇到了分段错误(请参见下面的详细输出)。 Can someone tell me why, and provide changes to the code that will make it work? 有人可以告诉我原因,并提供对代码的更改以使其起作用吗? Thanks. 谢谢。

Any observations on acceptable or professional coding style would be welcome also. 任何对可接受或专业编码风格的观察也将受到欢迎。


#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

class E {
    public:
        E() {cout << "In E constructor" << endl;}

        virtual ~E() {cout << "In E destructor" << endl;}
};

class E1 : public E {
    public:
        E1() {cout << "New E1" << endl;}

        ~E1() {cout << "In E1 destructor" << endl;}
};

class E2 : public E {
    public:
        E2() {cout << "New E2" << endl;}

        ~E2() {cout << "In E2 destructor" << endl;}
};

class D {
    public:
        D(const vector<int>& a, int b)
        {
            cout << "y1" << endl;
            if (b == 1)
                p = new E1();
            else
                p = new E2();
        }

        D() {cout << "y2" << endl; p = new E1();}

        ~D() {if (p != nullptr) {cout << "x" << endl; delete p;}}

    private:
        E *p;
};

int main(int argc, char **argv)
{
    D d;

    vector<int> a;
    a.push_back(1);

    int b = 2;

    d = D(a, b);
}

Here's the output. 这是输出。

y2
In E constructor
New E1
y1
In E constructor
New E2
x
In E2 destructor
In E destructor
x
Segmentation fault

Your original code is deleting the new'd E2 object twice due to the statement. 由于该语句,您的原始代码两次删除了新的E2对象。

   d = D(a, b);

Since you didn't provide an assignment operator, the compiler will provide a memberwise assignment implementation. 由于您没有提供赋值运算符,因此编译器将提供逐成员赋值实现。 Immediately after the assignment, both the variable d and the temporary, unnamed variable created from D(a, b) will have their p member variables pointing to the same E2 object. 赋值后,立即将变量d和从D(a,b)创建的临时未命名变量的p成员变量都指向同一E2对象。

The D::~D() destructor will be invoked on both the d and the unnamed variable. D ::〜D()析构函数将同时在d和未命名变量上调用。 Deleting the E2 object twice causes the segmentation fault. 两次删除E2​​对象会导致分段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM