From: Andrei Alexandrescu Date: Mon, 22 Oct 2012 21:42:05 +0000 (-0700) Subject: fbstring's front() and back() return by reference X-Git-Tag: v0.22.0~1167 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=99d9bfdd41e4999b2b5485a01b17a1a759fff559;p=folly.git fbstring's front() and back() return by reference 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 --- diff --git a/folly/FBString.h b/folly/FBString.h index 1c8ec1d3..7da9a306 100644 --- a/folly/FBString.h +++ b/folly/FBString.h @@ -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(); } diff --git a/folly/test/FBStringTest.cpp b/folly/test/FBStringTest.cpp index 0e6e57f1..bd13a669 100644 --- a/folly/test/FBStringTest.cpp +++ b/folly/test/FBStringTest.cpp @@ -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);