vendredi 19 août 2016

Why returning of vector by value of explicitly non-moveable and implicitly non-copyable type does NOT produce a compilation error?

I have this simple example holder class which is explicitly non-moveable:

template <typename T>
struct holder
{
    holder() = default;

    holder(const holder& b)
        : t(b.t)
    {
    }

    holder(holder&& b) = delete;

    holder& operator=(const holder& b)
    {
        t = b.t;
        return *this;
    }

    holder& operator=(holder&& b) = delete;

    T t;
};

The following type is therefore also implicitly non-copyable (because of std::unique_ptr being such):

typedef holder<std::unique_ptr<int>> ptr;

So, as I would expect if I have a function like ptr foo();, calling it by either auto x = foo; or ptr x; x = foo(); produces a compilation error that a deleted function is being called.

However if I introduce another type a vector of ptr like so:

typedef std::vector<ptr> vec;

vec foo();

int main()
{
    vec x = foo();
    x = foo();
    return 0;
}

...this compiles fine.

How come? How does this even work?

(an example of the successful compilation can be found here)

Aucun commentaire:

Enregistrer un commentaire