C++ 向量中的运动元素
我试图移动向量中的元素,这里是一个简化的例子C++ 向量中的运动元素,c++,c++11,move-semantics,C++,C++11,Move Semantics,我试图移动向量中的元素,这里是一个简化的例子 #include <iostream> #include <vector> struct A { A(size_t i) noexcept : i(i) { std::cout << "A-" << i << std::endl; } A(A const& a) noexcept : i(a.i) { std::cout << "A
#include <iostream>
#include <vector>
struct A
{
A(size_t i) noexcept : i(i)
{ std::cout << "A-" << i << std::endl; }
A(A const& a) noexcept : i(a.i)
{ std::cout << "A copy" << std::endl; }
void operator=(A const& a) noexcept
{
i = std::move(a.i);
std::cout << "A op=" << std::endl;
}
A(A&& a) noexcept : i(std::move(a.i))
{ std::cout << "A move" << std::endl; }
~A() noexcept { }
int i;
};
int main()
{
// A a0(0);
// A a1 = std::move(a0);
std::vector<A> v;
v.reserve(2);
v.emplace_back( 0 );
v.emplace_back( 1 );
v.emplace_back( 2 );
v[0] = std::move( v[2] );
v[2] = std::move( A(3) );
return 0;
}
您定义了移动构造函数,但未定义移动赋值
A& operator = (A&&);
您的常规赋值运算符应返回一个引用:
A& operator=(A const& a)
{
std::cout << "A op=" << std::endl;
return *this;
}
A&运算符=(A常量&A)
{
std::cout谢谢。我可以在7分钟后接受你的回答。我应该知道std::move返回了一个A&&
,并且我没有定义操作符=(A&&
函数。
A& operator=(A const& a)
{
std::cout << "A op=" << std::endl;
return *this;
}