2016-08-19 2 views
1

コンパイラがオブジェクトに対して一意の所有権セマンティクスを強制するようなC++クラスを作成する方法はありますか?コンパイラでC++クラスがオブジェクトの固有の所有権セマンティクスを強制

+6

あなたがしてください手の込んだことはできますか? – Rakete1111

+5

'std :: unique_ptr'に似ていますか? – AndyG

+0

さて、ctorをプライベートにし、友人の 'make_unique'にすることができます。しかし、誰かが自分のクラスを所有していることを制限する正当な理由は本当にありません。それは彼らの責任です。これは根本的に良いデザインに反するものです。 – David

答えて

4

はい。コピー/割り当てを無効にして移動を有効にするだけです。

私たちは便利な基底クラス(注意:仮想デストラクタを不要誰が今までこのクラスを介してオブジェクトを所有していないため):まで煮詰めることができ
struct unique_thing 
{ 
    unique_thing() = default; // you can create me 
    unique_thing(unique_thing&&) = default; // and move me 
    unique_thing(unique_thing const&) = delete; // but not copy me 

    unique_thing& operator=(unique_thing&&) = default; // you may move-assign me 
    unique_thing& operator=(unique_thing const&) = delete; // but not copy-assign me 
}; 

#include <utility> 
#include <type_traits> 
#include <cassert> 

struct only_moveable 
{ 
    protected: 
    constexpr only_moveable() noexcept = default; 
    constexpr only_moveable(only_moveable&&) noexcept = default; 
    constexpr only_moveable& operator=(only_moveable&&) noexcept {}; 
}; 

struct MyClass : only_moveable 
{ 
}; 


int main() 
{ 
    // creatable 
    MyClass a; 

    // move-constructible 
    MyClass b = std::move(a); 

    // move-assignable 
    a = std::move(b); 

    // not copy-constructible 
    assert((not std::is_copy_constructible<MyClass>::value)); 

    // not copy-assignable 
    assert((not std::is_copy_assignable<MyClass>::value)); 
} 

本のいくつかの一般的なモデルをイディオムは以下のとおりです。

  1. std::unique_ptr<>
  2. std::thread
  3. std::future<>
  4. std::unique_lock<>
  5. boost::asio::ip::tcp::socket
+2

Boost.Asioを参照する前に 'std :: thread'、' std :: unique_lock'、さらに 'std ::'と一般的な 'boost ::'の例を追加したいと思います。 – lisyarus

+0

Btw、あなたはコピーctorを削除し、 '='をコピーする必要はありません。それらは、ユーザが定義した( 'default'ed)move ctorと' = 'を動かすという意味では暗黙的に宣言されていません。 – HolyBlackCat

+2

その勾配は豪華です –

関連する問題