From d8d93ebf4ea53c974cdb9599c3fa3c1f20781e6c Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Thu, 20 Oct 2016 15:20:48 -0700 Subject: [PATCH] Prevent erroneous code like vector{{"this", "that"}} from compiling Summary: Someone debugged a runtime crash and traced it back to code like: `vector{{"this", "that"}}`. Presumably the user thought they were passing an initializer list of strings to the vector constructor. Instead, they constructed a single fbstring with two char pointers pointing into //different// strings. With the appropriate fbstring constructors, we can flag this as invalid at compile-time. Reviewed By: yfeldblum Differential Revision: D3927397 fbshipit-source-id: a5f335073fb55bbb703a23f06874238cbdb5d91a --- folly/FBString.h | 15 ++++++++++++++- folly/test/FBStringTest.cpp | 6 ++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/folly/FBString.h b/folly/FBString.h index bb3d339b..ab0c0d8f 100644 --- a/folly/FBString.h +++ b/folly/FBString.h @@ -1176,17 +1176,30 @@ public: InIt begin, InIt end, typename std::enable_if< - !std::is_same::value, + !std::is_convertible::value, const A>::type& /*a*/ = A()) { assign(begin, end); } // Specialization for const char*, const char* + // Note: it's a template to keep it from being preferred when called as + // basic_fbstring("hello", "world!"). + // See the constructor immediately below. + template FOLLY_MALLOC_NOINLINE basic_fbstring(const value_type* b, const value_type* e, const A& /*a*/ = A()) : store_(b, e - b) { } + // Nonstandard constructor. To make the following code fail to compile + // instead of silently selecting the {Iter,Iter} constructor and crashing + // at runtime: + // std::vector const foo{{"this", "that"}}; + template + basic_fbstring(const value_type (&/*x*/)[N], + const value_type (&/*y*/)[M], + const A& /*a*/ = A()) = delete; + // Nonstandard constructor basic_fbstring(value_type *s, size_type n, size_type c, AcquireMallocatedString a) diff --git a/folly/test/FBStringTest.cpp b/folly/test/FBStringTest.cpp index fb4a7991..4c7ba8f7 100644 --- a/folly/test/FBStringTest.cpp +++ b/folly/test/FBStringTest.cpp @@ -1426,3 +1426,9 @@ TEST(FBStringCtorTest, NullZeroConstruction) { folly::fbstring f(p, n); EXPECT_EQ(f.size(), 0); } + +// TEST(FBStringCtorTest, BadIteratorPair) { +// // Should fail to compile +// std::vector vs{{"hello", "world!"}}; +// EXPECT_EQ(vs.size(), 2u); +// } -- 2.34.1