考虑以下功能:
std::vector<int> pushIt(std::vector<int> v){
v.push_back(10);
return v;
}
int main(){
std::vector<int> vec;
vec = pushIt(std::move(vec));
}
Run Code Online (Sandbox Code Playgroud)
我的假设是向量移动到函数中,修改并移回其原始位置.这应该导致类似的行为,因为它作为非const引用传递.这似乎是非常有效的行为,但同事担心未定义的行为.这里有什么我想念的吗?
我想这样做是因为当前的功能
void currentPushIt(std::vector<int>& v){
v.push_back(10);
}
Run Code Online (Sandbox Code Playgroud)
在代码审查中导致了很多问题,因为人们忽略了一个无辜的调用currentPushIt(v)会使迭代器失效的事实.让他们写作v=pushIt(std::move(v))应该唤醒他们他们不会犯同样的错误.
根据 1.9p15,与参数相关的值计算和副作用在执行函数体之前进行排序。因此,当您输入时,pushIt源vec已被移走。然后在执行 后对赋值进行排序pushIt,因为您实际上是在调用用户定义的运算符vector::operator=:
vec.operator=( // sequenced after
pushIt( // the evaluation of this, which is sequenced after
std::move( // the evaluation of this
vec)))
Run Code Online (Sandbox Code Playgroud)
所以你的代码没问题。
| 归档时间: |
|
| 查看次数: |
168 次 |
| 最近记录: |