简体   繁体   English

在 C++ 中传递具有移动语义的 unique_ptr 向量

[英]Passing vector of unique_ptr with move semantics in c++

I am learning CPP++14 move semantics.While writing a small code I observed some weird behavior.我正在学习 CPP++14 移动语义。在编写一小段代码时,我观察到了一些奇怪的行为。 I am moving vector of unique ptr to a function using r-value refrence.我正在使用 r 值引用将唯一 ptr 的向量移动到函数。 on debuuging I found that the changes are being applied to the moved object also.在调试时,我发现更改也应用于移动的对象。 Why am I observing this hcnage even the object is moved?为什么即使物体被移动我也会观察这个hcnage? Whats does the move do in following code?以下代码中的移动有什么作用?

void func(std::vector<std::unique_ptr<int>> && vect) {
    vect.emplace_back(std::move(std::make_unique<int>(3)));
    return ;
}

int  main() {
    std::vector<std::unique_ptr<int>> a;
    func(std::move(a));
    cout<<(*(a[0]))<<endl;
    return 0;
}

Whats does the move do in following code?以下代码中的移动有什么作用?

Move operation is not performed in func(std::move(a)); func(std::move(a));不执行移动操作func(std::move(a)); in fact, std::move just performs conversion and produces an rvalue (xvalue) expression, which is just bound to the rvalue reference parameter vect of func .事实上, std::move只是执行转换并产生一个右值(xvalue)表达式,它只是绑定到func的右值引用参数vect Then any modification on vect inside func has effect on the argument (ie a ) too, they refer to the same object.然后在func内对vect任何修改vect对参数(即a )产生影响,它们引用同一个对象。

In particular, std::move produces an xvalue expression that identifies its argument t .特别是, std::move产生一个 xvalue 表达式来标识它的参数t It is exactly equivalent to a static_cast to an rvalue reference type.它完全等同于static_cast到右值引用类型。

If you change the parameter to pass-by-value, then you'll see move operation is performed.如果您将参数更改为按值传递,那么您将看到执行移动操作。 And given the usage you showed, just pass-by-lvalue-reference seems less confusing (and no need to use std::move on argument again).考虑到你展示的用法,只传递左值引用似乎不那么令人困惑(并且不需要再次在参数上使用std::move )。

BTW: In vect.emplace_back(std::move(std::make_unique<int>(3)));顺便说一句:在vect.emplace_back(std::move(std::make_unique<int>(3))); the usage of std::move is superfluous, std::make_unique<int>(3) been an rvalue expression. std::move的使用是多余的, std::make_unique<int>(3)是一个右值表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM