浏览代码

LibCore: Don't leak proto-Resources when loading non-existent paths

The construct `adopt_ref(*new Obj(TRY(get_resource())))` is another
manifestation of a classic anti-pattern. In old C++, you would leak the
object's memory if the argument threw an exception, or if a member
initializer threw an exception. In our case, we leak if the MappedFile
returns an Error. This is pretty concerning, and we should avoid this
pattern at all costs, and try to use the "safer" helpers whenever
possible.
Andrew Kaster 1 年之前
父节点
当前提交
d253beb2f7
共有 1 个文件被更改,包括 4 次插入2 次删除
  1. 4 2
      Userland/Libraries/LibCore/ResourceImplementation.cpp

+ 4 - 2
Userland/Libraries/LibCore/ResourceImplementation.cpp

@@ -50,9 +50,11 @@ ErrorOr<NonnullRefPtr<Resource>> ResourceImplementation::load_from_uri(StringVie
 
 
     if (uri.starts_with(file_scheme)) {
     if (uri.starts_with(file_scheme)) {
         auto path = uri.substring_view(file_scheme.length());
         auto path = uri.substring_view(file_scheme.length());
+        auto utf8_path = TRY(String::from_utf8(path));
         if (is_directory(path))
         if (is_directory(path))
-            return adopt_ref(*new Resource(TRY(String::from_utf8(path)), Resource::Scheme::File, Resource::DirectoryTag {}));
-        return adopt_ref(*new Resource(TRY(String::from_utf8(path)), Resource::Scheme::File, TRY(MappedFile::map(path))));
+            return adopt_ref(*new Resource(utf8_path, Resource::Scheme::File, Resource::DirectoryTag {}));
+        auto mapped_file = TRY(MappedFile::map(path));
+        return adopt_ref(*new Resource(utf8_path, Resource::Scheme::File, move(mapped_file)));
     }
     }
 
 
     dbgln("ResourceImplementation: Unknown scheme for {}", uri);
     dbgln("ResourceImplementation: Unknown scheme for {}", uri);