移动构造函数何时被调用? [英] When Does Move Constructor get called?
问题描述
我对何时调用move构造函数与copy构造函数感到困惑。
我已经阅读以下来源:
I'm confused about when a move constructor gets called vs a copy constructor. I've read the following sources:
Move constructor is not getting called in C++0x
所有这些来源要么过于复杂(我只想举一个简单的例子),要么仅显示如何编写move构造函数,而不是如何调用它。我已经写了一个更具体的简单问题:
All of these sources are either overcomplicated(I just want a simple example) or only show how to write a move constructor, but not how to call it. Ive written a simple problem to be more specific:
const class noConstruct{}NoConstruct;
class a
{
private:
int *Array;
public:
a();
a(noConstruct);
a(const a&);
a& operator=(const a&);
a(a&&);
a& operator=(a&&);
~a();
};
a::a()
{
Array=new int[5]{1,2,3,4,5};
}
a::a(noConstruct Parameter)
{
Array=nullptr;
}
a::a(const a& Old): Array(Old.Array)
{
}
a& a::operator=(const a&Old)
{
delete[] Array;
Array=new int[5];
for (int i=0;i!=5;i++)
{
Array[i]=Old.Array[i];
}
return *this;
}
a::a(a&&Old)
{
Array=Old.Array;
Old.Array=nullptr;
}
a& a::operator=(a&&Old)
{
Array=Old.Array;
Old.Array=nullptr;
return *this;
}
a::~a()
{
delete[] Array;
}
int main()
{
a A(NoConstruct),B(NoConstruct),C;
A=C;
B=C;
}
当前A,B和C都有不同的指针值。我希望A具有一个新的指针,B具有C的旧指针,C具有空指针。
currently A,B,and C all have different pointer values. I would like A to have a new pointer, B to have C's old pointer, and C to have a null pointer.
有些不对劲,但是如果有人可以建议一个文档,我可以详细了解这些新功能,我将不胜感激,并且可能不需要提出更多问题。
somewhat off topic, but If one could suggest a documentation where i could learn about these new features in detail i would be grateful and would probably not need to ask many more questions.
推荐答案
移动构造函数称为:
- 当对象初始化程序为
std :: move(something)
- 当对象初始化程序为
std :: forward< T>(某物)
和T
不是左值引用类型(在模板编程中用于完美转发) - 当对象初始化程序是临时的并且编译器没有消除时按值返回函数局部类对象并且编译器没有完全消除复制/移动时
- 抛出函数局部的类对象,编译器不会消除全部吃完了副本/移动
- when an object initializer is
std::move(something)
- when an object initializer is
std::forward<T>(something)
andT
is not an lvalue reference type (useful in template programming for "perfect forwarding") - when an object initializer is a temporary and the compiler doesn't eliminate the copy/move entirely
- when returning a function-local class object by value and the compiler doesn't eliminate the copy/move entirely
- when throwing a function-local class object and the compiler doesn't eliminate the copy/move entirely
这不是完整的列表。请注意,如果参数具有类类型(非引用),则对象初始化器可以是函数参数。
This is not a complete list. Note that an "object initializer" can be a function argument, if the parameter has a class type (not reference).
a RetByValue() {
a obj;
return obj; // Might call move ctor, or no ctor.
}
void TakeByValue(a);
int main() {
a a1;
a a2 = a1; // copy ctor
a a3 = std::move(a1); // move ctor
TakeByValue(std::move(a2)); // Might call move ctor, or no ctor.
a a4 = RetByValue(); // Might call move ctor, or no ctor.
a1 = RetByValue(); // Calls move assignment, a::operator=(a&&)
}
这篇关于移动构造函数何时被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!