質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
C++

C++はC言語をもとにしてつくられた最もよく使われるマルチパラダイムプログラミング言語の1つです。オブジェクト指向、ジェネリック、命令型など広く対応しており、多目的に使用されています。

Q&A

解決済

2回答

1244閲覧

デストラクタのclose

Y.R.T

総合スコア42

C++

C++はC言語をもとにしてつくられた最もよく使われるマルチパラダイムプログラミング言語の1つです。オブジェクト指向、ジェネリック、命令型など広く対応しており、多目的に使用されています。

0グッド

0クリップ

投稿2020/08/29 07:08

下記構文のデストラクタで、

~unique_handle() noexcept { Traits::close(m_value); }

とあります

m_valueをcloseするとはどういう意味なのでしょうか?
これをしなければどうなりますか?

#ifdef _WIN32 #include <windows.h> #else typedef void* HANDLE; #define DWORD unsigned long #ifdef _LP64 #define LONG_PTR long long #define ULONG_PTR unsigned long long #else #define LONG_PTR long #define ULONG_PTR unsigned long #endif #define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1) struct SECURITY_ATTRIBUTES { DWORD nLength; void* lpSecurityDescriptor; int bInheritHandle; }; struct OVERLAPPED { ULONG_PTR Internal; ULONG_PTR InternalHigh; union { struct { DWORD Offset; DWORD OffsetHigh; } DUMMYSTRUCTNAME; void* Pointer; } DUMMYUNIONNAME; HANDLE hEvent; }; int CloseHandle(HANDLE hObject) { return 0; } HANDLE CreateFile(char const*, DWORD, DWORD, SECURITY_ATTRIBUTES*, DWORD, DWORD, HANDLE) { return INVALID_HANDLE_VALUE; } int ReadFile(HANDLE, void*, DWORD, DWORD*, OVERLAPPED*) { return 0; } #define GENERIC_READ 0x80000000L #define GENERIC_WRITE 0x40000000L #define CREATE_NEW 1 #define CREATE_ALWAYS 2 #define OPEN_EXISTING 3 #define OPEN_ALWAYS 4 #define TRUNCATE_EXISTING 5 #define FILE_SHARE_READ 1 #define FILE_ATTRIBUTE_NORMAL 0x00000080 #endif #ifdef _UNICODE #define _T(x) L ## x #else #define _T(x) #endif #include <stdio.h> #include <algorithm> #include <vector> #include <stdexcept> #include <iostream> template <typename Traits> class unique_handle { using pointer = typename Traits::pointer; pointer m_value; public: unique_handle(unique_handle const&) = delete; unique_handle& operator=(unique_handle const&) = delete; explicit unique_handle(pointer value = Traits::invalid()) noexcept :m_value{ value } {} unique_handle(unique_handle&& other) noexcept : m_value{ other.release() } {} unique_handle& operator=(unique_handle&& other) noexcept { if (this != &other) { reset(other.release()); } return *this; } ~unique_handle() noexcept { Traits::close(m_value); } explicit operator bool() const noexcept { return m_value != Traits::invalid(); } pointer get() const noexcept { return m_value; } pointer release() noexcept { auto value = m_value; m_value = Traits::invalid(); return value; } bool reset(pointer value = Traits::invalid()) noexcept { if (m_value != value) { Traits::close(m_value); m_value = value; } return static_cast<bool>(*this); } void swap(unique_handle<Traits>& other) noexcept { std::swap(m_value, other.m_value); } }; template <typename Traits> void swap(unique_handle<Traits>& left, unique_handle<Traits>& right) noexcept { left.swap(right); } template <typename Traits> bool operator==( unique_handle<Traits> const& left, unique_handle<Traits> const& right) noexcept { return left.get() == right.get(); } template <typename Traits> bool operator!=( unique_handle<Traits> const& left, unique_handle<Traits> const& right) noexcept { return left.get() != right.get(); } struct null_handle_traits { using pointer = HANDLE; static pointer invalid() noexcept { return nullptr; } static void close(pointer value) noexcept { CloseHandle(value); } }; struct invalid_handle_traits { using pointer = HANDLE; static pointer invalid() noexcept { return INVALID_HANDLE_VALUE; } static void close(pointer value) noexcept { CloseHandle(value); } }; using null_handle = unique_handle<null_handle_traits>; using invalid_handle = unique_handle<invalid_handle_traits>; void function_that_throws() { throw std::runtime_error("an error has occurred"); } void bad_handle_example() { bool condition1 = false; bool condition2 = true; HANDLE handle = CreateFile(_T("server_setting.txt"), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); //HANDLE handle = CreateFile(_T("sample.txt"), // GENERIC_READ, // FILE_SHARE_READ, // nullptr, // CREATE_ALWAYS, // FILE_ATTRIBUTE_NORMAL, // nullptr); if (handle == INVALID_HANDLE_VALUE) return; if (condition1) { CloseHandle(handle); return; } std::vector<char> buffer(1024); unsigned long bytesRead = 0; ReadFile(handle, buffer.data(), buffer.size(), &bytesRead, nullptr); if (condition2) { // oops, forgot to close handle return; } // throws exception; the next line will not execute function_that_throws(); CloseHandle(handle); } void good_handle_example() { bool condition1 = false; bool condition2 = true; invalid_handle handle{ CreateFile(_T("server_setting.txt"), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) }; if (!handle) return; if (condition1) return; std::vector<char> buffer(1024); unsigned long bytesRead = 0; ReadFile(handle.get(), buffer.data(), buffer.size(), &bytesRead, nullptr); if (condition2) return; function_that_throws(); } int main() { try { bad_handle_example(); } //catch (...) {} catch (const std::runtime_error& e) { // 例外が発生した! std::cout << e.what() << std::endl; std::exit(1); } try { good_handle_example(); } //catch (...) {} catch (const std::runtime_error& e) { // 例外が発生した! std::cout << e.what() << std::endl; std::exit(1); } return 0; }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

ベストアンサー

C++

1template <typename Traits> 2class unique_handle { 3public: 4 ~unique_handle() noexcept { 5 Traits::close(m_value); 6 } 7 ... 8};

なんだから、デストラクト時に Traits::close(m_value) される、と。
これで何が起こるかは Traits::close 次第です。
たとえば

C++

1struct invalid_handle_traits { 2 using pointer = HANDLE; 3 4 static pointer invalid() noexcept { 5 return INVALID_HANDLE_VALUE; 6 } 7 8 static void close(pointer value) noexcept { 9 CloseHandle(value); 10 } 11};

コレ↑が Traitsとして使われたなら

~unique_handle() noexcept { CloseHandle(m_value); }

と同じことです。

投稿2020/08/29 07:28

episteme

総合スコア16614

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

この場合での Traits::close は結果的に null_handle_traitsinvalid_handle_traitsclose なので Traits::close(m_value);CloseHandle(m_value) としたのと同じことになります。 もちろん unique_handle を実体化するときの型引数として別の型 (トレイツ) を与えれば別の動作をするでしょう。

Windows API における HANDLE などはデストラクタを持たないので陽に閉じる必要があり、そういったものを C++ の一般的なオブジェクトと同じようにデストラクタで解体するようにラッピングする意図が unique_handle にはあるようです。 ハンドルの性質によっては CloseHandle 以外の方法で後始末する必要があったりもするでしょうから、そういった性質はトレイツとして切り出しています。

やや複雑ではありますが書いてある通りなので何を説明すればよいのか難しいのですが、知りたいのは以上のようなことで良いのでしょうか。

投稿2020/08/29 07:34

SaitoAtsushi

総合スコア5437

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Y.R.T

2020/08/29 07:59

ありがとうございます。 理解できました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問