Make QStringLiteral always choke on non-literals
authorThiago Macieira <thiago.macieira@intel.com>
Mon, 21 May 2012 11:30:49 +0000 (13:30 +0200)
committerQt by Nokia <qt-info@nokia.com>
Mon, 21 May 2012 14:02:06 +0000 (16:02 +0200)
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 <qthjk@ovi.com>
Reviewed-by: Olivier Goffart <ogoffart@woboq.com>
src/corelib/tools/qstring.h

index 7b6d784..965bfb0 100644 (file)
@@ -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) \