gpt4 book ai didi

c++ - std::forward Visual Studio 13 的行为与我预期的不同

转载 作者:行者123 更新时间:2023-11-28 02:03:13 25 4
gpt4 key购买 nike

我正在尝试学习一些基本的 C++ 11,使用 Scott Meyers 在 youtube 上的讲座“An Effective C++11/14 Sampler”

https://www.youtube.com/watch?v=BezbcQIuCsY

使用他的示例代码 std::forward (讲座第 19 分钟)我写了下面的代码来理解 std::forward 的效果

#include "stdafx.h"
#include <string>
#include <utility>

class A
{
public:
void Foo(std::string&& s)
{
std::string s2 = std::forward<std::string>(s);
}
};

int _tmain(int argc, _TCHAR* argv[])
{
A a;

std::string s3 = "Hello World";
a.Foo(s3);
a.Foo("Hello World");

return 0;
}

令人惊讶的是它没有编译,a.Foo(s3)不能隐式地从左值转换为右值。所以我改变了a.Foo(s3);a.Foo(std::move(s3));现在它编译了。但是,在两次调用 Foo std::forward<std::string>(s); 时解析为右值并发生移动操作(s 被重置为 "" 因为它的缓冲区被窃取)。

所以我真的不明白good是什么std::forward以及何时适用。我在这里错过了什么?

最佳答案

调用 std::forward<>当不涉及模板参数推导/引用折叠时没有意义。

转发引用(Scott Meyers 曾将其称为“通用引用”)的要点是,根据您所接收内容的值(value)类别,您也可以转发该值类别。

但是在这里,您根本不会对什么是值类别感到困惑,它是静态的。

这是一个具有模板参数推导的上下文:

template<typename T>
void f(T&& t) // T is to be deduced, && might be collapsed
{
g(std::forward<T>(t)); // will keep the category value
}

f(std::string{"hey"}); // T inferred std::string&&, so the parameter type is `std::string&& &&`, which is collapsed to `std::string &&`.

关于c++ - std::forward Visual Studio 13 的行为与我预期的不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38544349/

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