I have been looking at changing some code to make use of QStringBuilder
expression template for its purported performance improvements. Unfortunately this resulted in sections of my code starting to crash in places, an example of which follows:
#define QT_USE_QSTRINGBUILDER
#include <numeric>
#include <vector>
#include <QString>
#include <QStringBuilder>
int main()
{
std::vector<int> vals = {0, 1, 2, 3, 4};
QString text = "Values: " + QString::number(vals[0]);
text = std::accumulate(vals.begin() + 1, vals.end(), text, [](const QString& s, int i)
{
return s + ", " + QString::number(i);
});
}
The reason this crashes is because the return type of the lambda expression is deduced to be QStringBuilder<QStringBuilder<QString,const char [3]>,QString>
which after being returned attempts to cast to QString
to assign to the accumulate
result. This cast crashes because it is attempting to use references to objects which were in the scope of the lambda and have now been destroyed. This crash can be fixed by explicitly specifying the return type of the lambda as such [](const QString& s, int i) -> QString
which ensures that the cast occurs before the closure is exited.
However the fact that enabling QStringBuilder
here caused a crash in previously working code without even emitting a warning means that I will now avoid using it elsewhere unless I can guarantee that this will not happen again. Since in this case RVO could prevent any copying from occurring I don't think the usual technique of disabling copying of the object would work. Is there a way to prevent this occurring in QStringBuilder
or similar expression templates or are objects which maintain references to automatic variables always going to be unsafe to use?
QStringBuilder
is C++11-compatible, but not C++14-compatible at the moment...This is essentially a C++14, not C++11 question. – Intermeddle