DEKKER
DEKKER

Reputation: 921

can not use auto for declaring variables

Why in the code below I can not use the auto keyword? I am not sure if this is a Qt related problem or a c++ thing?

#include <QFile>

void foo(const QString& path) {
    auto f = QFile(path); // Error: QFile is marked as deletet here
    QFile file(path); // works fine!!!
}

Upvotes: 0

Views: 267

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597051

In a variable declaration, auto deduces the type from the initializer value. If you can't specify an initializer, then you can't use auto.

In C++17 and later, there is guaranteed copy elision, so auto f = QFile(path); will get deduced as QFile f = QFile(path); as expected, and then it will be optimized further to just QFile f(path);, eliminating any need for creating a temporary QFile from path and copying it to f.

Prior to C++17, that optimization is not guaranteed, it may or may not happen. So, while auto f = QFile(path); will still deduce to QFile f = QFile(path);, that will not work if a temporary QFile is created from path, as that temporary cannot be copied into f because QFile's copy constructor is delete'd to prevent copies (see Why QObject subclasses are not copyable).

So, it would seem your compiler is not performing that optimization, hence the error message, and thus no opportunity to use auto for declaring f, unless your compiler implements copy elision on function return values at least, or if QFile has a move constructor, eg:

#include <QFile>

QFile getQFileFromPath(const QString& path) {
    return QFile(path);
}

void foo(const QString& path) {
    auto f = getQFileFromPath(path);
}

Upvotes: 4

JarMan
JarMan

Reputation: 8277

The problem is not the auto. It's that you're implicitly using the copy constructor, which is not allowed for any QObject-derived class. It also would not work if you did this:

QFile f = QFile(path);

Upvotes: 9

Related Questions