dimanche 3 juillet 2016

will move constructors automatically initialize unlisted members?

If I have this class:

class Foo {
public:
    Foo() = default;

    // version 1 move constructor
    Foo(Foo &&f) : v_() {
        v_.swap(f.v_);
    }

    // version 2 move constructor
    Foo(Foo &&f) : v_(), m_() {
        v_.swap(f.v_);
    }

private:
    std::vector<int> v_;
    std::mutex m_;
};

void bar(Foo &&f) {
    // construct a new object from f
    Foo f2(std::move(f)); // f2's value before calling constructor is undefined
}

Is there any difference between the 2 move constructors? Does the mutex m_ get initialized automatically in version 1 or do I need to explicitly list it as in version 2?

Note that I'm not swapping the mutexes, there's no need to do that (I'm explicitly marking the move constructor as not thread safe because it can't be due to other reasons).

Aucun commentaire:

Enregistrer un commentaire