c++ - 这个列表是垃圾内存吗?

标签 c++ qt c++11

我有两个这样的类:

foo.h

class A //base class
{
public:
    A(QList<int> &timers, QList<int> &positions);
    int pIndex = 0;
    QList<int> timers;
    QList<int> positions;
};


class B : public A
{
public:
    B();
private:
    QList<int> t { 5, 8, 10, 20, 25 };
    QList<int> p { 10, 15, 20 };
};

foo.cpp

B::B()
    : A(t, p)
{
}

A::A(QList<int> &t, QList<int> &p)
{
    foreach (int v, t) {
       qDebug() << "v = " << v;
    }

    //this->timers = t;
    //this->positions = p;
}

但是当我初始化 B 类时,它崩溃并提示 SGIFAULT。

auto b = new B();

出现此错误我错过了什么?起初我以为是我传递的 QList 有时变成了垃圾内存但是这段代码遵循相同的原则但使用了 int[]相反 QList<int>确实工作正常:

class A
{
public:
    A(int p[3]) 
    {
        this->v = p;
    }

    void print()
    {
        for(int i = 0; i < 3; ++i)
        {
            printf("v = %d\n", v[i]);
        }
    }
private:
    int *v = NULL;
};

class B : public A
{
public:
    B() : A(values) 
    {
    }
private:
    int values[3] = {1, 2, 3};
};

int main() {
    A *o = new B();
    o->print();
}

最佳答案

问题是,当你调用基类构造函数时,tp 还没有构造:

检查一下(static 成员是在创建任何类对象之前构造的,请注意这可能不是您正在寻找的解决方案):

class B : public A
{
public:
    B();
private:
    static QList<int> t;
    static QList<int> p;
};

QList<int> B::t { 5, 8, 10, 20, 25 };
QList<int> B::p { 10, 15, 20 };

现在编译输出

5
8
10
20
25

此外,您没有将第二个 QList 传递给基类构造函数。

替代版本:

class A
{
public:
    //const references
    A(const QList<int> &timers, const QList<int> &positions);
    int pIndex = 0;
    QList<int> timers;
    QList<int> positions;
};


class B : public A
{
public:
    B();
private:
    // no need for QList members
};


B::B()
    : A({ 5, 8, 10, 20, 25 }, { 10, 15, 20 }) // use initializer lists directly
{
}

A::A(const QList<int> &t, const QList<int> &p)
{
    for (int v : t) {
       qDebug() << "v = " << v;
    }
}

int main()
{
    auto b = new B();
    delete b;
}

关于c++ - 这个列表是垃圾内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38555927/

相关文章:

C++11 修改 std::discrete_distribution 中的值

c++ - 运行使用 MinGW 构建的可执行文件时出现缺少 msvcr100.dll 错误

c++ - 使用 Qt 解析 JSON 数组

qt - QObject 在放入 QML 变量后被销毁

qt - 如何在 Qt Creator 中使用 MinGW-64

c++ - 向上转换为基类时如何使用继承的类成员的值

c++ - 具有指向对象指针的 std::vector 的未指定行为

C++11 正则表达式,非贪婪

c++ - 是否有异步方式知道文件已更改?

c++ - unordered_map::find with key std::pair of pointers with custom hash crashes in VS2012