Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ ユニークポインタの受け渡し | スマートポインタの導入
C++スマートポインタ

bookユニークポインタの受け渡し

メニューを表示するにはスワイプしてください

ポインタと動的メモリ割り当て静的変数よりも選択する主な理由の一つは、コードのさまざまな部分でデータを柔軟に受け渡しできる点にあります。しかし、ユニークポインタの場合、この受け渡しには少し注意が必要です。

ビルダ関数から返す場合

ユニークポインタを受け渡す有効なケースの一つは、ビルダ関数(リソースの割り当てや構築のみを目的とした関数)から返す場合です。

unique_pointer_builder.cpp

unique_pointer_builder.cpp

copy
123456789101112131415
#include <iostream> #include <memory> std::unique_ptr<int> unique_ptr_builder() { return std::make_unique<int>(42); } int main() { // This will be the sole owner of the dynamically allocated integer 42 std::unique_ptr<int> p_unique = unique_ptr_builder(); if (p_unique) std::cout << "Value from unique pointer: " << *p_unique << std::endl; else std::cout << "Unique pointer is null." << std::endl; }

ビルダ関数を使用して、int値へのユニークポインタを作成。関数が戻ると、unique_ptr関数内のmainが動的な整数値を指すようになる。

所有権の移譲時

ユニークポインタをmoveすることも有効かつ安全とされる。例えば、ユニークポインタの所有権をclass Aからclass Bへ移譲することができる。

transferring_ownership.h

transferring_ownership.h

copy
12345
// Create a unique pointer inside classA classA->source_ptr = std::make_unique<int>(42); // Later, move the ownership to classB, this is perfectly fine classB->target_ptr = std::move(sourcePtr);

ユニークポインタを渡すべきでない場合

std::unique_ptr複数の所有者で共有する目的で渡すことは不適切。これはユニークポインタの本質である「唯一の所有者」という概念を損なうためです。

クラス内でユニークポインタのインスタンスを作成し、その 生ポインタ を外部ライブラリ関数に渡すこともありますが、このような共有は 安全ではなくデバッグが困難な メモリ問題を引き起こす可能性があります。

passing_raw_pointer.h

passing_raw_pointer.h

copy
12345
// Create a unique pointer. std::unique_ptr<std::string> p_unique = std::make_unique<int>(33); // Extract the raw pointer and pass it to an external class. ExternalClass obj(p_unique.get()); // Never do this, not safe.
question mark

ユニークポインタを渡すのが適切とされるのはどのような場合ですか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  5

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  5
some-alt