隐式声明的移动赋值运算符
Implicitly-declared move assignment operator
我无法理解 cpp 参考中的这个简单规则;
If no user-defined move assignment operators are provided for a class
type (struct, class, or union), and all of the following is true:
there are no user-declared copy constructors;
there are no user-declared move constructors;
there are no user-declared copy assignment operators;
there are no user-declared destructors;
the implicitly-declared move assignment operator would not be defined
as deleted, (until C++14)
THEN the compiler WILL declare a move assignment operator as an inline public member of its class with the signature T& T::operator=(T&&).
考虑到这一点,考虑
struct bar
{
bar(int i) : _i(i) {};
bar (const bar& other) { };
bar (bar& other) { };
int _i;
};
后面跟着这个,说;
bar b2(2);
bar b3(3);
cout << "b3._i " << b3._i << endl << endl;
b3 = std::move(b2);
cout << "b3._i " << b3._i << endl;
我们得到的输出是;
b3._i 3
b3._i 2
所以我们有一个动作发生了;
b3 = std::move(b2);
我没有定义那个移动赋值运算符,所以它是由编译器隐式为我定义的。但是我 已经 打破了规定的条件,我有一个用户定义的复制构造器....但是编译器生成的移动仍然发生了。我明显误解了文字,谁能开导我一下?
谢谢,祝你有愉快的一天。
G
So here we have a move happening;
b3 = std::move(b2);
不,这是副本。 std::move(b2)
只是将 b2
转换为 bar&&
。 bar&&
然后在 implicitly-generated copy-assignment 运算符中绑定到 const bar&
。
我无法理解 cpp 参考中的这个简单规则;
If no user-defined move assignment operators are provided for a class type (struct, class, or union), and all of the following is true:
there are no user-declared copy constructors;
there are no user-declared move constructors;
there are no user-declared copy assignment operators;
there are no user-declared destructors;
the implicitly-declared move assignment operator would not be defined as deleted, (until C++14)
THEN the compiler WILL declare a move assignment operator as an inline public member of its class with the signature T& T::operator=(T&&).
考虑到这一点,考虑
struct bar
{
bar(int i) : _i(i) {};
bar (const bar& other) { };
bar (bar& other) { };
int _i;
};
后面跟着这个,说;
bar b2(2);
bar b3(3);
cout << "b3._i " << b3._i << endl << endl;
b3 = std::move(b2);
cout << "b3._i " << b3._i << endl;
我们得到的输出是;
b3._i 3
b3._i 2
所以我们有一个动作发生了;
b3 = std::move(b2);
我没有定义那个移动赋值运算符,所以它是由编译器隐式为我定义的。但是我 已经 打破了规定的条件,我有一个用户定义的复制构造器....但是编译器生成的移动仍然发生了。我明显误解了文字,谁能开导我一下?
谢谢,祝你有愉快的一天。
G
So here we have a move happening;
b3 = std::move(b2);
不,这是副本。 std::move(b2)
只是将 b2
转换为 bar&&
。 bar&&
然后在 implicitly-generated copy-assignment 运算符中绑定到 const bar&
。