From 09c90c9fc3f30a4ef5166afa6c5c81aab7ac278e Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Mon, 21 May 2012 13:30:49 +0200 Subject: [PATCH] Make QStringLiteral always choke on non-literals MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit The fallback implementation of QStringLiteral did not (up to now) enforce the need to use a literal. So it was possible to write: const char *foo = "Hello"; QString s = QStringLiteral(foo); Which would do the wrong thing and create s == "Hel" on 32-bit platforms (sizeof(foo) == 4) or, wrose, s == "Hello\0XY" on 64-bit platforms (sizeof(foo) == 8, X and Y are garbage). This change enforces the need for a literal by producing errors on the above cases, as well as when foo is a char array variable. GCC: error: expected ‘)’ before ‘foo’ Clang (abbreviated): error: expected ')' namespace X { QString x() { const char foo[42] = "Hello"; return QStringLiteral(foo); } } ^ note: to match this '(' ^ ICC: error: expected a ")" namespace X { QString x() { const char foo[42] = "Hello"; return QStringLiteral(foo); } } ^ The first C++11 error currently is: error: expected primary-expression before ‘enum’ (GCC) error: expected a ")" (ICC) Change-Id: I317173421dbd7404987601230456471c93b122ed Reviewed-by: hjk Reviewed-by: Olivier Goffart --- src/corelib/tools/qstring.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/tools/qstring.h b/src/corelib/tools/qstring.h index 7b6d784..965bfb0 100644 --- a/src/corelib/tools/qstring.h +++ b/src/corelib/tools/qstring.h @@ -153,7 +153,7 @@ Q_STATIC_ASSERT_X(sizeof(qunicodechar) == 2, // fallback, return a temporary QString // source code is assumed to be encoded in UTF-8 -# define QStringLiteral(str) QString::fromUtf8(str, sizeof(str) - 1) +# define QStringLiteral(str) QString::fromUtf8("" str "", sizeof(str) - 1) #endif #define Q_STATIC_STRING_DATA_HEADER_INITIALIZER_WITH_OFFSET(size, offset) \ -- 2.7.4