diff --git a/AK/String.cpp b/AK/String.cpp index 96ccb18544..f6d7f2dc1f 100644 --- a/AK/String.cpp +++ b/AK/String.cpp @@ -215,10 +215,15 @@ String& String::operator=(String&& other) String& String::operator=(String const& other) { if (&other != this) { + if (!is_short_string()) + m_data->unref(); + m_data = other.m_data; + if (!is_short_string()) m_data->ref(); } + return *this; } diff --git a/Tests/AK/TestString.cpp b/Tests/AK/TestString.cpp index 02514c1c92..e48bb9c6be 100644 --- a/Tests/AK/TestString.cpp +++ b/Tests/AK/TestString.cpp @@ -39,6 +39,26 @@ TEST_CASE(move_assignment) EXPECT_EQ(string1, "friends!"sv); } +TEST_CASE(copy_assignment) +{ + auto test = [](auto string1, auto string2) { + string1 = string2; + EXPECT_EQ(string1, string2); + }; + + test(String {}, String {}); + test(String {}, "abc"_string); + test(String {}, "long string"_string); + + test("abc"_string, String {}); + test("abc"_string, "abc"_string); + test("abc"_string, "long string"_string); + + test("long string"_string, String {}); + test("long string"_string, "abc"_string); + test("long string"_string, "long string"_string); +} + TEST_CASE(short_strings) { #ifdef AK_ARCH_64_BIT