How to deal with noncopyable objects when inserting to containers in C++

后端 未结 2 794
旧时难觅i
旧时难觅i 2021-02-07 18:31

I\'m looking for the best-practice of dealing with non-copyable objects.

I have a mutex class, that obviously should not be copyable. I added a private copy constructor

2条回答
  •  时光取名叫无心
    2021-02-07 18:58

    If they are non-copyable, the container has to store (smart) pointers to those objects, or reference wrappers, etc, although with C++0x, noncopyable objects can still be movable (like boost threads), so that they can be stored in containers as-is.

    to give examples: reference wrapper (aka boost::ref, a pointer under the hood)

    #include 
    #include 
    struct Noncopy {
    private:
            Noncopy(const Noncopy&) {}
    public:
            Noncopy() {}
    };
    int main()
    {
            std::vector > v;
            Noncopy m;
            v.push_back(std::tr1::reference_wrapper(m));
    }
    

    C++0x, tested with gcc:

    #include 
    struct Movable {
    private:
            Movable(const Movable&) = delete;
    public:
            Movable() {}
            Movable(Movable&&) {}
    };
    int main()
    {
            std::vector v;
            Movable m;
            v.emplace_back(std::move(m));
    }
    

    EDIT: Nevermind, C++0x FCD says, under 30.4.1/3,

    A Mutex type shall not be copyable nor movable.

    So you're better off with pointers to them. Smart or otherwise wrapped as necessary.

提交回复
热议问题