Frage

I would like to return a default Null value for a method returning a QList<float*> (in case processing fails, I want to return).

How to build a Null QList<float*> properly?

War es hilfreich?

Lösung

In general, there's no such thing as a "null value" for non-pointer types. Options include:

  • Throw an exception on failure
  • Return an empty list, if that can never be a valid result
  • Return a nullable wrapper type, like boost::optional<QList> or std::pair<bool, QList>

Andere Tipps

return a pointer to a QList then test it for null pointer, i think this is what your asking anyway, sorry if i misinterpreted

void someClass::test()
{
    std::shared_ptr<QList<float> > testList = doSomething()
    if(testList == nulllptr)
    {
        // Then its null
    }
    else
    {
       // Do whatever you want with it
    }
}

std::shared_ptr<QList<float>> someClass::doSomething()
{
    std::shared_ptr<QList<float>> someList; // = NULL at the moment 

    if(weWantValues) // Lets just pretend this bool knows if we want values 
    {
        someList = std::make_shared<QList<float>(); // now a shared pointer to a list
        // Populate with whatever values you want. use ".get()" or "->" to access list
    }

    // this may be null or populated so check if it == nullptr before using
    // Like we do in the function above
    return someList;
}

You can use return {} instead of nullptr, like this:

QList<QObject *> getModel(int id)
{
    if (id < 0)
        return {};

    return m_myModel->model();
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top