Search code examples
c++11constructormove

Why do I need the move constructor, if the constructor take values


I have the following example:

 #include <cstdint>
class A
{
public:
    A(const A&) = delete;
    A& operator = (const A&) = delete;
    A(A&&) = default; // why do I need the move constructor
    A&& operator = (A&&) = delete;
    explicit A(uint8_t Val)
    {
        _val = Val;
    }
    virtual ~A() = default;
private:
    uint8_t _val = 0U;
};
class B
{
public:
    B(const B&) = delete;
    B& operator = (const B&) = delete;
    B(B&&) = delete;
    B&& operator = (B&&) = delete;

    B() = default;
    virtual ~B() = default;
private:
    A _a = A(4U); // call the overloaded constructor of class A
};

int main()
{
    B b;
    return 0;
}

why do I need the move-constructor "A(A&&) = default;" in A? I could not the code line where the mentioned move-constructor is called.

Many thanks in advance.


Solution

  • A _a = A(4U) in this case depends on the move constructor.

    This type of initialization is called copy initialization, and according to the standard it may invoke the move constructor, see 9.3/14.