c++ - Can a unique_ptr<>() initialization fail? -
from documentation of std::unique_ptr<>(), may happen when initializing pointer not clear me.
when allocating std::shared_ptr<>()
, allocates memory buffer handle reference counter. may std::bad_alloc
exception.
could similar happen when initializing unique pointer?
i asking question because if does, may lose attempting have delete through unique pointer. example:
void deleter(file * f) { fclose(f); } void func() { ... file * f(fopen("/tmp/random", o_creat | ...)); if(f == nullptr) ...handle error... std::unique_ptr<file, decltype(&deleter)> raii_file(f, deleter); ... }
so, if initialization of unique_ptr<>()
can throw, may end keeping file f
open forever. (i use file *
example, similar resource affected.)
opposed this answer, cannot use std::make_unique<>()
since i'm not allocating memory.
would safer initialize std::unique_ptr<>()
before fopen()
, , save value in there after?
... std::unique_ptr<file, decltype(&deleter)> raii_file(nullptr, deleter); file * f(fopen("/tmp/random", o_creat | ...)); if(f == nullptr) ...handle error... raii_file = f; ...
or have similar problems?
all of unique_ptr
's constructors noexcept
. no, there's no way can fail. if deleter
type throws on copy/move, noexcept
catch , call std::terminate
.
Comments
Post a Comment