ICU-21778 UnicodeString::clone error handling fix

Change UnicodeString::clone() to return a nullptr if the underlying copy
constructor produces a bogus string. This can happen if the copy constructor
encounters a memory allocation failure in allocating the copy's internal string
buffer, or if the string being copied was already bogus.

The change is consistent with other ICU clone functions, which are generally
defined to return nullptr in case of errors.
This commit is contained in:
Andy Heninger 2021-10-29 17:17:41 -07:00
parent 698efda42b
commit fd5a346b3d
2 changed files with 12 additions and 1 deletions

View file

@ -334,7 +334,8 @@ Replaceable::clone() const {
// UnicodeString overrides clone() with a real implementation
UnicodeString *
UnicodeString::clone() const {
return new UnicodeString(*this);
LocalPointer<UnicodeString> clonedString(new UnicodeString(*this));
return clonedString.isValid() && !clonedString->isBogus() ? clonedString.orphan() : nullptr;
}
//========================================

View file

@ -1653,6 +1653,16 @@ UnicodeStringTest::TestBogus() {
if(test1>=test2 || !(test2>test1) || test1.compare(test2)>=0 || !(test2.compare(test1)>0)) {
errln("bogus<empty failed");
}
// test that copy constructor of bogus is bogus & clone of bogus is nullptr
{
test3.setToBogus();
UnicodeString test3Copy(test3);
UnicodeString *test3Clone = test3.clone();
assertTrue(WHERE, test3.isBogus());
assertTrue(WHERE, test3Copy.isBogus());
assertTrue(WHERE, test3Clone == nullptr);
}
}
// StringEnumeration ------------------------------------------------------- ***