gpt4 book ai didi

c++ - 在 C++ 中传递具有移动语义的 unique_ptr vector

转载 作者:行者123 更新时间:2023-12-03 06:51:48 24 4
gpt4 key购买 nike

我正在学习 CPP++14 移动语义。在编写小代码时,我观察到一些奇怪的行为。我正在使用 r 值引用将唯一 ptr 的 vector 移动到函数中。在调试时,我发现更改也应用于移动的对象。为什么即使物体被移动,我也会观察到这种情况?以下代码中的移动有什么作用?

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?

func(std::move(a)); 中未执行移动操作事实上, std::move 只是执行转换并产生一个右值(xvalue)表达式,它只是绑定(bind)到右值引用参数 vectfunc .然后对 vect 进行任何修改里面 func对参数(即 a )也有影响,它们指的是同一个对象。

In particular, std::move produces an xvalue expression that identifies its argument t. It is exactly equivalent to a static_cast to an rvalue reference type.


如果您将参数更改为按值传递,那么您将看到执行了移动操作。鉴于您展示的用法,仅传递左值引用似乎不那么令人困惑(并且无需再次在参数上使用 std::move)。
顺便说一句:在 vect.emplace_back(std::move(std::make_unique<int>(3))); std::move的用法是多余的, std::make_unique<int>(3)是一个右值表达式。

关于c++ - 在 C++ 中传递具有移动语义的 unique_ptr vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63744593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com