Home > front end >  Is move elision guaranteed in this case?
Is move elision guaranteed in this case?

Time:09-10

Consider the following C 20 code; assume T to be non-movable and non-copyable:

struct Cell
{
    Cell(T&& instance) : obj(std::move(instance)) {}

private:
    T obj;
};

Cell cell(T{/* arguments */});

Is move elision guaranteed in the constructor of Cell?

If T were movable, would it be guaranteed that only the regular (non-move) constructor would be invoked?

CodePudding user response:

Is move elision guaranteed in the constructor of Cell?

No, the parameter instance of Cell::Cell(T&& instance) is of rvalue reference type T&&, so there can be no move elision here. The parameter instance must bind to the materialized temporary T{/* arguments */}. Then, std::move(instance) will be used to direct initialize obj.

But note that obj(std::move(instance) won't work because you're trying to initialize obj with std::move(instance) when T is neither movable neither copyable. Demo

  • Related