gpt4 book ai didi

c++ - 参数传递与右值的混淆?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:49 25 4
gpt4 key购买 nike

我对通过函数调用传递右值有点困惑,请参阅下面的代码:

#include <string>
#include <iostream>

void func(std::string & s, char a) {
std::cout << "here1" << std::endl;
// ...
}

void func(std::string && s, char a) {
std::cout << "here2" << std::endl;
// ...
}

void foo(std::string && s) {
func(s, ':');
}

int main(int agrc, char *argv[])
{
std::string s = "a:b:c:d";
func(std::move(s), ':'); // print here2
char s2[8] = "a:b:c:d";
func(std::move(std::string(s2)), ':'); // print here2
foo(std::move(s2)); // print here1, why?
return 0;
}

g++-4.7 demo.cpp -std=c++11

为什么最后一个案例(使用 foo)打印 here1

在我看来,在函数 foo 中,s 是一个右值,所以它会打印 here2

更新:

foo 中的

s 是一个左值,但是没有必要写foo 的重载版本:

void foo(std::string & s) {
func(s, ':');
}

因为编译器可以知道输入参数s是右值还是左值,但为什么编译器在右值情况下不自动 move s

最佳答案

foo 的声明:

void foo(std::string && s) {
func(s, ':');
}

表示它可以接受一个右值引用,这个信息用于方法解析。但是,在 foo 中,参数有一个名称,因此是一个左值引用。基本上它已经退化为左值引用。

如果您想在调用 func 时将其视为右值引用,则需要通过将其转回未命名实例来将其转换回右值引用。这就是 std::move 完成的。

关于c++ - 参数传递与右值的混淆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21132581/

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