如果构造函数采用值,为什么我需要移动构造函数
Why do I need the move constructor, if the constructor take values
我有以下例子:
#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;
}
为什么我需要 A 中的移动构造函数 "A(A&&) = default;"?我无法调用提到的移动构造函数的代码行。
非常感谢。
A _a = A(4U)
在这种情况下取决于移动构造函数。
这种类型的初始化称为复制初始化,根据标准它可以调用移动构造函数,参见9.3/14。
我有以下例子:
#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;
}
为什么我需要 A 中的移动构造函数 "A(A&&) = default;"?我无法调用提到的移动构造函数的代码行。
非常感谢。
A _a = A(4U)
在这种情况下取决于移动构造函数。
这种类型的初始化称为复制初始化,根据标准它可以调用移动构造函数,参见9.3/14。