Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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)

like image 310
Borislav Stanimirov Avatar asked Aug 19 '16 07:08

Borislav Stanimirov


1 Answers

Let alone RVO, a vector is movable independently from the element type's characteristics.

like image 60
Shoe Avatar answered Oct 20 '22 21:10

Shoe