fbstring's front() and back() return by reference
authorAndrei Alexandrescu <aalexandre@fb.com>
Mon, 22 Oct 2012 21:42:05 +0000 (14:42 -0700)
committerJordan DeLong <jdelong@fb.com>
Mon, 29 Oct 2012 23:32:19 +0000 (16:32 -0700)
Summary: C++11 added front() and back() that return by reference. fbstring also added front() and back() as non-standard convenience functions, which returned by value. This diff aligns fbstring with the standard.

Test Plan: added and ran unittest

Reviewed By: delong.j@fb.com

FB internal diff: D607574

folly/FBString.h
folly/test/FBStringTest.cpp

index 1c8ec1d308a5d9b39233d9411e435461d5d167b9..7da9a3068a8d349155f03f5187b05d65282454af 100644 (file)
@@ -1131,14 +1131,24 @@ public:
     return const_reverse_iterator(begin());
   }
 
-  // Non-standard functions. They intentionally return by value to
-  // reduce pressure on the reference counting mechanism.
-  value_type front() const { return *begin(); }
-  value_type back() const {
+  // Added by C++11
+  // C++11 21.4.5, element access:
+  const value_type& front() const { return *begin(); }
+  const value_type& back() const {
     assert(!empty());
-    return begin()[size() - 1];
+    // Should be begin()[size() - 1], but that branches twice
+    return *(end() - 1);
+  }
+  value_type& front() { return *begin(); }
+  value_type& back() {
+    assert(!empty());
+    // Should be begin()[size() - 1], but that branches twice
+    return *(end() - 1);
+  }
+  void pop_back() {
+    assert(!empty());
+    store_.shrink(1);
   }
-  void pop_back() { assert(!empty()); store_.shrink(1); }
 
   // 21.3.3 capacity:
   size_type size() const { return store_.size(); }
index 0e6e57f1b1c6c664b097e282ab0154cc119a68ee..bd13a669441b1c6ad01add74e642f41070e1eeb4 100644 (file)
@@ -1007,6 +1007,17 @@ TEST(FBString, testHash) {
   EXPECT_NE(hashfunc(a), hashfunc(b));
 }
 
+TEST(FBString, testFrontBack) {
+  fbstring str("hello");
+  EXPECT_EQ(str.front(), 'h');
+  EXPECT_EQ(str.back(), 'o');
+  str.front() = 'H';
+  EXPECT_EQ(str.front(), 'H');
+  str.back() = 'O';
+  EXPECT_EQ(str.back(), 'O');
+  EXPECT_EQ(str, "HellO");
+}
+
 int main(int argc, char** argv) {
   testing::InitGoogleTest(&argc, argv);
   google::ParseCommandLineFlags(&argc, &argv, true);