سؤال

Have a class which have the following functions:

FileInfoWrapper(const QFileInfo &_fileInfo) : fileInfo(_fileInfo) {}

const QString& FileName() const { return fileInfo.fileName(); }

But when I do this:

QFileInfo info(somePath);

qDebug() << info.absoluteDir(); // works

FileInfoWrapper test(info);

qDebug() << test.FileName(); // this crashes the entire application

When I remove the const & from the string return, it works. It's like << doesn't work with references. Whats wrong and why does it crash?

هل كانت مفيدة؟

المحلول

You return reference to the QString which is destroyed when you leave FileName() function.

نصائح أخرى

std::cout doesn't know QString, you need to convert it to std::string or const char*

Use QString::toStdString to convert to std::string, e.g.:

std::cout << test.FileName().toStdString();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top