Commit 99d9bfdd authored by Andrei Alexandrescu's avatar Andrei Alexandrescu Committed by Jordan DeLong

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
parent a8991a6b
...@@ -1131,14 +1131,24 @@ public: ...@@ -1131,14 +1131,24 @@ public:
return const_reverse_iterator(begin()); return const_reverse_iterator(begin());
} }
// Non-standard functions. They intentionally return by value to // Added by C++11
// reduce pressure on the reference counting mechanism. // C++11 21.4.5, element access:
value_type front() const { return *begin(); } const value_type& front() const { return *begin(); }
value_type back() const { const value_type& back() const {
assert(!empty()); 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: // 21.3.3 capacity:
size_type size() const { return store_.size(); } size_type size() const { return store_.size(); }
......
...@@ -1007,6 +1007,17 @@ TEST(FBString, testHash) { ...@@ -1007,6 +1007,17 @@ TEST(FBString, testHash) {
EXPECT_NE(hashfunc(a), hashfunc(b)); 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) { int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
google::ParseCommandLineFlags(&argc, &argv, true); google::ParseCommandLineFlags(&argc, &argv, true);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment