gpt4 book ai didi

c++ - std::move 作为参数的参数类型

转载 作者:行者123 更新时间:2023-12-01 14:37:02 25 4
gpt4 key购买 nike

https://stackoverflow.com/a/18300974/462608

If you pass an rvalue reference to another function, you are passing anamed object, so, the object isn't received like a temporal object.

void some_function(A&& a)
{
other_function(a);
}

The object a would be copied to the actual parameter ofother_function. If you want the object a continues being treated as atemporary object, you should use the std::move function:

other_function(std::move(a));

other_function 的参数类型是什么?

不可能是 other_function( A&& xyz ) 因为如果是这样的话就不需要 std::move 了?

最佳答案

您可以使用这个简单的代码进行测试

#include <iostream>

struct A{};

void other_function(A&) {
std::cout << "L-value\n";
}

void other_function(A&&) {
std::cout << "R-value\n";
}

void some_function(A&& a)
{
other_function(a); // a is an L-value
}

int main() {
A a;
some_function(std::move(a));
other_function(std::move(a));
return 0;

}

输出:

L-value
R-value

这是完美转发的测试:

#include <iostream>

struct A{};

void other_function(A&) {
std::cout << "L-value\n";
}

void other_function(A&&) {
std::cout << "R-value\n";
}

template<typename T>
void some_function(T&& a)
{
other_function(std::forward<T>(a));
}

int main() {
A a;
some_function(a);
some_function(std::move(a));
return 0;

}

输出

L-value
R-value

关于c++ - std::move 作为参数的参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63687805/

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