2
#include <vector>
#include <iostream>
#include <memory>
int main()
{
// create the vector
std::vector< std::unique_ptr<int> > v;
for (int i = 0; i < 5; ++ i)
{
std::unique_ptr<int> newItem(new int(i));
v.push_back(std::move(newItem));
}
std::cout<<"vector's size before the move = " << v.size() << std::endl;
// move one item
auto it = move(v[2]);
std::cout<<"moved element = " << *it << std::endl;
std::cout<<"vector's size after the move = " << v.size() << std::endl;
if (nullptr == v[2].get())
std::cout<<"it is nullptr" << std::endl;
}
上面的示例将一个元素移出矢量,但矢量的大小保持不变。什么包含被移动的矢量元素?
什么包含移动后移动的元素?访问该元素是不是一个未定义的行为?它是nullptr(该示例打印它为空)?
这样做的理由是,移动的元素必须是在破坏的状态。 –
+1。虽然,我敢说,一个移动任务不应该等同于一个交换,因为这可能会让一些资源分配一段意想不到的时间。所以,案例(3)不是我所期望的。 – sellibitze
@sellobitze:不,我不打算将其作为一种常见做法的例子,就像某些合法的事情一样,因此如果事情真的发生,您也无法对此感到愤怒。 –