开发者

Object does not exist after constructor?

开发者 https://www.devze.com 2022-12-25 18:50 出处:网络
I have a constructor that looks like this (in c++): Interpreter::Interpreter() { tempDat == new DataObject();

I have a constructor that looks like this (in c++):

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

the constructor of dataObject does absolutely nothing, and clear does this:

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

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

}

Those members are defined as follows:

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

Now the strange thing is that I'm getting a segfault on tempDat->clear(); gdb says tempDat is null. How is that possible? The constructor of tempDat cannot fail, it looks like this:

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

}

I know there are probably better way's of making such a data struc开发者_Python百科ture, but I really like to know where this segfault problem is coming from..


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

You're using == to assign. Use = instead:

        tempDat = new DataObject();

Using == gives you an expression that compares the current value of tempDat (some random garbage) to the address of the newly created DataObject. The result of that expression is immediately discarded, and tempDat remains unchanged. So it still contains random garbage, which happened to be 0 in your debugging session.

0

精彩评论

暂无评论...
验证码 换一张
取 消