Which std types are guaranteed to be empty/null after being used as arg in move constructor

后端 未结 2 1649
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 22:13

I know shared_ptr, unique_ptr, weak_ptr are guaranteed to be empty after used as RVR argument in the constructor of the same type, but

2条回答
  •  -上瘾入骨i
    2020-12-16 22:34

    A rule of thumb

    As a rule of thumb: The move-only types or types with shared reference semantics leave their moved-from object in an empty state. All other types leave unspecified values.

    Move-only types

    Move-only types (which leave moved-from objects in an empty state) are std::unique_lock, std::thread, std::promise, std::packaged_task, std::future, basic_filebuf, std::basic_ifstream, std::basic_ofstream, std::basic_fstream, std::shared_lock and std::unique_ptr.

    Shared reference semantics

    Types with shared reference semantics are std::shared_future, and of course std::shared_ptr and std::weak_ptr. These leave their moved-from objects also in an empty state.

    A notable exception

    As I went through the standard library, I found std::stringstream and its input-only and output-only siblings (std::istringstream and std::ostringstream) as a notable exception. These classes are move-only, but nothing is being told about the moved-from object upon move-construction. Therefore, the valid-but-unspecified-rule applies. As you see, it's just a rule of thumb, not 100% always correct.

提交回复
热议问题