[PATCH] D27721: Add a c_str() member to StringLiteral

Zachary Turner via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Tue Dec 13 15:50:13 PST 2016


zturner updated this revision to Diff 81319.
zturner added a comment.

rsmith showed me some magic to make clang error on constructing a `StringLiteral` with a non-literal.  Unfortunately it still doesn't prevent someone declaring one in a non constexpr context, i.e. you can still write:  `StringLiteral S = "foo";` instead of `constexpr StringLiteral S = "foo";`, I don't think anyone has come up with a way to prevent the former yet, but this is at least better than before.


https://reviews.llvm.org/D27721

Files:
  include/llvm/ADT/StringRef.h


Index: include/llvm/ADT/StringRef.h
===================================================================
--- include/llvm/ADT/StringRef.h
+++ include/llvm/ADT/StringRef.h
@@ -838,22 +838,22 @@
 
   /// A wrapper around a string literal that serves as a proxy for constructing
   /// global tables of StringRefs with the length computed at compile time.
-  /// Using this class with a non-literal char array is considered undefined
-  /// behavior.  To prevent this, it is recommended that StringLiteral *only*
-  /// be used in a constexpr context, as such:
+  /// StringLiteral should *only* be used in a constexpr context, as such:
   ///
   /// constexpr StringLiteral S("test");
   ///
-  /// Note: There is a subtle behavioral difference in the constructor of
-  /// StringRef and StringLiteral, as illustrated below:
-  ///
-  /// constexpr StringLiteral S("a\0b");  // S.size() == 3
-  /// StringRef S("a\0b");  // S.size() == 1
-  ///
   class StringLiteral : public StringRef {
   public:
     template <size_t N>
-    constexpr StringLiteral(const char (&Str)[N]) : StringRef(Str, N - 1) {}
+    constexpr StringLiteral(const char (&Str)[N])
+#if __has_attribute(enable_if)
+        __attribute((enable_if(__builtin_strlen(Str) == N - 1,
+                               "invalid string literal")))
+#endif
+        : StringRef(Str, N - 1) {
+    }
+
+    const char *c_str() const { return data(); }
   };
 
   /// @name StringRef Comparison Operators


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D27721.81319.patch
Type: text/x-patch
Size: 1461 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20161213/2cba402e/attachment.bin>


More information about the llvm-commits mailing list