重用已移动的容器? [英] Reusing a moved container?

查看:104
本文介绍了重用已移动的容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重新使用移动的容器的正确方法是什么?

  std :: vector< int&容器; 
container.push_back(1);
auto container2 = std :: move(container);

// ver1:Do nothing
//container2.clear(); // ver2:Reset
container = std :: vector< int>()// ver3:Reinitialize

container.push_back(2);
assert(container.size()== 1&& container.front()== 2);

根据我在C ++ 0x标准草案中读到的内容; ver3似乎是正确的方式,因为移动之后的对象是在


除非另有规定,将
放在一个有效但未指定的状态。


我从来没有找到任何



虽然我发现ver3有点迂回,并且更喜欢ver1,虽然vec3可以允许一些额外的优化,但另一方面很容易导致错误。 p>

我的假设是否正确?

解决方案

spec有效但未指定的状态:


未指定的对象状态,除了满足对象的不变量,为其类型指定[例如:如果类型 std :: vector< int> 的对象 x 有效但未指定的状态, x.empty()可以是
无条件调用, x.front()只有在 x.empty()返回false时才能被调用。 -end example]


因此,对象是活的。您可以执行不需要前提条件的任何操作(除非您首先验证前提条件)。



清除例如,没有前提条件。它会将对象返回到已知状态。所以只要清除它,并使用它正常。


What is the correct way to reuse a moved container?

std::vector<int> container;
container.push_back(1);
auto container2 = std::move(container);

// ver1: Do nothing
//container2.clear(); // ver2: "Reset"
container = std::vector<int>() // ver3: Reinitialize

container.push_back(2);
assert(container.size() == 1 && container.front() == 2);

From what I've read in the C++0x standard draft; ver3 seems to be the correct way, since an object after move is in a

"Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state."

I have never found any instance where it is "otherwise specified".

Although I find ver3 a bit roundabout and would have much preferred ver1, though vec3 can allow some additional optimization, but on the other hand can easily lead to mistakes.

Is my assumption correct?

解决方案

From section 17.3.26 of the spec "valid but unspecified state":

an object state that is not specified except that the object’s invariants are met and operations on the object behave as specified for its type [ Example: If an object x of type std::vector<int> is in a valid but unspecified state, x.empty() can be called unconditionally, and x.front() can be called only if x.empty() returns false. —end example ]

Therefore, the object is live. You can perform any operation that does not require a precondition (unless you verify the precondition first).

clear, for example, has no preconditions. And it will return the object to a known state. So just clear it and use it as normal.

这篇关于重用已移动的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆