std::shared_ptr<T>::reset
提供: cppreference.com
< cpp | memory | shared ptr
void reset() noexcept; |
(1) | (C++11以上) |
template< class Y > void reset( Y* ptr ); |
(2) | (C++11以上) |
template< class Y, class Deleter > void reset( Y* ptr, Deleter d ); |
(3) | (C++11以上) |
template< class Y, class Deleter, class Alloc > void reset( Y* ptr, Deleter d, Alloc alloc ); |
(4) | (C++11以上) |
管理対象オブジェクトを ptr
が指しているオブジェクトで置き換えます。 管理対象オブジェクトを所有する shared_ptr
オブジェクトがなくなったときにそのオブジェクトを破棄するために後に使用される、オプショナルなデリータ d
を指定できます。 デフォルトではデリータとして delete 式が使用されます。 供給された型に対応する正しい delete 式が必ず選択されます。 これがこの関数が別の引数 Y
を使用するテンプレートとして実装されている理由です。
*this
がすでにオブジェクトを所有していて、それがそのオブジェクトを所有する最後の shared_ptr
である場合、所有しているデリータを通してそのオブジェクトが破棄されます。
ptr
の指すオブジェクトがすでに所有されている場合、この関数は未定義動作の結果になります。
1) 管理対象オブジェクトがあれば、それを解放します。 呼び出し後、 *this の管理するオブジェクトはなくなります。 shared_ptr().swap(*this); と同等です。
2-4) 管理対象オブジェクトを
ptr
の指すオブジェクトで置き換えます。 Y
は完全型かつ T
に暗黙に変換可能でなければなりません。 さらに、2) デリータとして delete 式を使用します。 有効な delete 式が利用可能、すなわち delete ptr が well-formed でなければならず、 well-defined な動作を持たなければならず、いかなる例外も投げてはなりません。 shared_ptr<T>(ptr).swap(*this); と同等です。
3) デリータとして指定されたデリータ
d
を使用します。 Deleter
は型 T
に対して呼び出し可能、すなわち d(ptr) が well-formed でなければならず、 well-defined な動作を持たなければならず、いかなる例外も投げてはなりません。 Deleter
は CopyConstructible でなければならず、そのコピーコンストラクタおよびデストラクタは例外を投げてはなりません。 shared_ptr<T>(ptr, d).swap(*this); と同等です。4) (3) と同じですが、さらに内部使用のデータ確保のために
alloc
のコピーを使用します。 Alloc
は Allocator でなければなりません。 そのコピーコンストラクタおよびデストラクタは例外を投げてはなりません。 shared_ptr<T>(ptr, d, alloc).swap(*this); と同等です。目次 |
[編集] 引数
ptr | - | 所有権を取得するオブジェクトを指すポインタ |
d | - | オブジェクトの削除のために格納するデリータ |
alloc | - | 内部確保のために使用するアロケータ |
[編集] 戻り値
(なし)
[編集] 例外
[編集] 例
Run this code
#include <memory> #include <iostream> struct Foo { Foo(int n = 0) noexcept : bar(n) { std::cout << "Foo: constructor, bar = " << bar << '\n'; } ~Foo() { std::cout << "Foo: destructor, bar = " << bar << '\n'; } int getBar() const noexcept { return bar; } private: int bar; }; int main() { std::shared_ptr<Foo> sptr = std::make_shared<Foo>(1); std::cout << "The first Foo's bar is " << sptr->getBar() << "\n"; // reset the shared_ptr, hand it a fresh instance of Foo // (the old instance will be destroyed after this call) sptr.reset(new Foo); std::cout << "The second Foo's bar is " << sptr->getBar() << "\n"; }
出力:
Foo: constructor, bar = 1 The first Foo's bar is 1 Foo: constructor, bar = 0 Foo: destructor, bar = 1 The second Foo's bar is 0 Foo: destructor, bar = 0
[編集] 関連項目
新しい shared_ptr を構築します (パブリックメンバ関数) |