How to prevent QStringBuilder from outliving the s

2019-07-14 13:24发布

问题:

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?

回答1:

The lambda should return an explicit type:

[]() -> Type { }

or 

[]() -> QString { }


回答2:

The clazy code checker provides a check for this scenario.