简体   繁体   中英

Segmentation Fault on QObject cast

The values are like is not null, canconvert is true and is valid. But still segmentation fault occurs when trying to cast. I am debugging and the value set might have been deleted just before setValue is called with a new value.

QVariant m_model = 0;

is a member var

void Handler::setValue(const QVariant &var)
{
    bool isNull = m_model.isNull();
    bool canConvert = m_model.canConvert<QObject*>();
    bool isValid = m_model.isValid();

    if(!m_model.isNull() && m_model.canConvert<QObject*>()) {
        bool sConverts = (nullptr != m_model.value<QObject*>());
    }

    m_model = var;
}

Can someone tell why it crashes when still m_model has some data in it.

First some problems with your code:

QVariant::canConvert() returns whether the type of the value is convertible at all, not if the actually contained value can be converted. Example: you create a QVariant with a QString as value. Calling myValue.canConvert<double>() will return true , even if your string was "nonsense". That's because QVariant is generally able to convert strings like "1.0" to a double value of 1.0.

QVariant::isValid() returns whether the contained type is not QMetaType::UnknownType . This mostly only happens when you create a QVariant without assigning a value.

QVariant m_model = 0; will create a QVariant with type int. Don't do that. Just declare it without the = 0 part. QVariant (like other value types in Qt, ie QString, QSize etc.) doesn't need to be initialized to be null, empty or invalid. Declaring it like you did will make isValid() return true , though you might intend it to return false .

That said, i'm unsure of what you want to achieve in your code snippet. Basically you're testing m_model before assigning a new untested value var to it (why???).

As you said your value var (or probably the contained value) might have been deleted just before setValue() is called. If the QObject has been deleted and the pointer has not been set to nullptr explicitly you're handing a QVariant with a dangling pointer to the function. As setValue() doesn't test the new value var you will have that same dangling pointer in m_model , resulting in a crash whenever you try accesing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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