[llvm] r286139 - Disallow StringRef assignment from temporary std::strings.

Jordan Rose via llvm-commits llvm-commits at lists.llvm.org
Mon Nov 7 12:34:17 PST 2016


Author: jrose
Date: Mon Nov  7 14:34:16 2016
New Revision: 286139

URL: http://llvm.org/viewvc/llvm-project?rev=286139&view=rev
Log:
Disallow StringRef assignment from temporary std::strings.

Similar to r283798, this prevents accidentally referring to temporary
storage that goes out of scope by the end of the statement:

  someStringRef = getStringByValue();
  someStringRef = (Twine("-") + otherString).str();

Note that once again the constructor still has this problem:

  StringRef someStringRef = getStringByValue();

because once again we occasionally rely on this in calls:

  takesStringRef(getStringByValue());
  takesStringRef(Twine("-") + otherString);

Still, it's a step.

Modified:
    llvm/trunk/include/llvm/ADT/StringRef.h

Modified: llvm/trunk/include/llvm/ADT/StringRef.h
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/ADT/StringRef.h?rev=286139&r1=286138&r2=286139&view=diff
==============================================================================
--- llvm/trunk/include/llvm/ADT/StringRef.h (original)
+++ llvm/trunk/include/llvm/ADT/StringRef.h Mon Nov  7 14:34:16 2016
@@ -226,6 +226,15 @@ namespace llvm {
       return Data[Index];
     }
 
+    /// Disallow accidental assignment from a temporary std::string.
+    ///
+    /// The declaration here is extra complicated so that `stringRef = {}`
+    /// and `stringRef = "abc"` continue to select the move assignment operator.
+    template <typename T>
+    typename std::enable_if<std::is_same<T, std::string>::value,
+                            StringRef>::type &
+    operator=(T &&Str) = delete;
+
     /// @}
     /// @name Type Conversions
     /// @{




More information about the llvm-commits mailing list