Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QVector of struct - no appropriate default constructor available

I'm very confused as to why this isn't working. I must be misunderstanding something key about QVectors...

I've created an MCVE to show the issue:

#include <QCoreApplication>
#include <QVector>

struct ChunkRequest
{
    ChunkRequest(int x, int z)
    {
        this->x = x;
        this->z = z;
    }

    int x;
    int z;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QVector<ChunkRequest> requestedChunks;

    requestedChunks.append(ChunkRequest(1, 2));

    return a.exec();
}

Compiling throws an error C2512: 'ChunkRequest' : no appropriate default constructor available

I am able to create a ChunkRequest variable with ChunkRequest req(1, 2); but as soon as I try to append it to my QVector the error throws.

I am legitimately confused as to why.

EDIT: After reading your comments, it is clear to me that QVector requires a default constructor in order to determine the size of each element in the array. But this doesn't answer why.

If a struct has a certain number of members and each member has a known size in memory (even pointers to dynamic memory are known size) then I don't see why QVector requires a default constructor? The size should be known at compile time... right?

like image 695
mrg95 Avatar asked Apr 01 '18 20:04

mrg95


1 Answers

In C++ specifying any constructor for a struct (or class) instructs the compiler not to provide a default constructor automatically. It's a quirk of the language.

This becomes a problem for container classes such as QVector which can resize on the fly (either internally or explicitly.) When allocating new objects to fill the space it will call the default constructor -- but if there isn't a default constructor available a compile-time error will occur.

The problem can be solved by specifying a default constructor, even if it doesn't do anything, for example:

ChunkRequest() {}
like image 162
MrEricSir Avatar answered Sep 29 '22 04:09

MrEricSir