How does a C++ compiler decide when to call a move constructor for std::vector or any object
本问题已经有最佳答案,请猛点这里访问。
我读的是标准模板图书馆的书,并与下面列出的STL容器章节的细节相混淆。显然,它指定了std::vector操作和效果
1 2 3 4 5 6 | Operation Effect vector<Elem> c(c2) | Copy constructor; creates a new vector as a copy of c2 (all elements are copied) vector<Elem> c = c2 | Copy constructor; creates a new vector as a copy of c2 (all elements are copied) vector<Elem> c(rv) | Move constructor; creates a new vector, taking the contents of the rvalue rv (since C++11) vector<Elem> c = rv | Move constructor; creates a new vector, taking the contents of the rvalue rv (since C++11) |
显然,move和copy构造函数的语法没有区别,它们究竟是何时调用的?
(P)The move constructor is called where it makes sense to call it,i.e.moving an object and using it there does not make sense,as the original object has been modified(possibly),which is not desirable:(p)字母名称(P)So,in that case,the copy constructor is called:(p)字母名称(P)但是,在这里,它并不要求移动的建设者,因为它是有利于维护,或是一个临时价值:(p)字母名称(P)"EDOCX1矢量"是指一种暂时的矢量,如果它已经被修改了,谁会在乎呢?你永远不会知道,作为向量将被摧毁作为EDOCX1,你一直在努力。共享时间向量将只是一个时间的浪费。(p)
(P)Let you say you have a function EDOCX1 plus 0 that returns a vector by value:(p)字母名称(P)The value returned by the function is an rvalue.(p)(P)And they lets say you want to call this function to initialize a vector of your rs:(p)字母名称(P)Now the compiler knows the vector returned by EDOCX1 commercial 0 will not be used any more,it's a temporary object,there doesn't make sense to copy this temporary object since it will just be destructed a t once way.只要竞争对手决定呼吁移动建设者敦促。(p)
(P)Perhaps you should decouple syntax from seminatics for better understanding.让我做一个分析,考虑这个代码。(p)字母名称(P)Now,if you find the following line,what constructor will be called?(p)字母名称(P)You can't tell it because you don't know whether EDOCX1 big 3 has type int or std:这在你的例子中没有多大区别,但随着时间的推移,每周一次的竞争将检查辩论是一种保留还是不保留。如果这是一个EDOCX1的标语4,那么,这一标语4将提供A(MOVE)建筑商Overload和EDOCX1的标语3,这是一个Rvalue reference,它们将是首选的。(p)
布尔奇1(P)不知道,这是真的。这不具体为EDOCX1,英文本2,但一般来说,所有类型。COPY-initialization by copy and by move have exactly the same syntax.Same goes for copy-assignment.(p)(P)The difference comes from the type of argument expression.When the argument is a non-const R-value,the move constructor/assignment is prefered by overload resolution.Otherwise,move-constructor is not applicable,so copy constructor is used.(p)布尔奇1(P)RV and C2 appear to not be objects.他们是表达的苹果人。The book could be clearer about that(maybe it is,the excerpt is out of context after all).(p)
(P)Copy Constructor Syntax:分类(Const classname&)(p)(P)Syntax of move constructor:分类,分类,分类,分类,分类(p)(P)但是,他们的声明是不同的。(p)(P)答:(p)(P)http://en.cppreference.com/w/cpp/language/copy-uu constructorhttp://en.cppreference.com/w/cpp/language/move/(p)