【问题标题】:Object does not exist after constructor?构造函数后对象不存在?
【发布时间】:2010-04-03 10:12:33
【问题描述】:

我有一个看起来像这样的构造函数(在 c++ 中):

Interpreter::Interpreter() {
        tempDat == new DataObject();
        tempDat->clear();
}

dataObject 的构造函数什么都不做,clear 是这样做的:

bool DataObject::clear() {
        //clear the object

        if (current_max_id > 0) {
            indexTypeLookup.clear();
            intData.clear();
            doubleData.clear();
            current_max_id = 0;
        }

}

这些成员定义如下:

std::map<int, int> indexTypeLookup;
std::map<int, int> intData;
std::map<int, double> doubleData;

现在奇怪的是我在 tempDat->clear(); 上遇到了段错误。 gdb 说 tempDat 为空。这怎么可能? tempDat 的构造函数不能失败,看起来是这样的:

DataObject::DataObject() : current_max_id(0)
{

}

我知道可能有更好的方法来制作这样的数据结构,但我真的很想知道这个段错误问题来自哪里..

【问题讨论】:

    标签: c++ constructor map object segmentation-fault


    【解决方案1】:
    Interpreter::Interpreter() {
            tempDat == new DataObject(); // <- here
            tempDat->clear();
    }
    

    您正在使用== 进行分配。请改用=

            tempDat = new DataObject();
    

    使用== 为您提供了一个将tempDat(一些随机垃圾)的当前值与新创建的DataObject 的地址进行比较的表达式。该表达式的结果立即被丢弃,tempDat 保持不变。所以它仍然包含随机垃圾,在您的调试会话中恰好是0

    【讨论】:

    • 卫生署! (那是多么愚蠢....)谢谢,我找了一个小时没看到...
    猜你喜欢
    • 1970-01-01
    • 2013-10-20
    • 2021-10-22
    • 1970-01-01
    • 2017-06-03
    • 2017-11-10
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多