下面的简单代码显示,static_cast到r值引用类型和std::move可能会根据被初始化对象的类型,在初始化语句中更改它们的输入参数(这里是变量inupt)。有人能解释一下这种行为吗?
我至少感到高兴的是,static_cast和std::move的行为类似,因为std::move确实在幕后使用了static_cast。
#include <iostream>
#include <string>
int main() {
{
std::string input("hello");
std::string&& result = static_cast<std::string&&>(input);
std::cout << "cast case 1: input: " << input << " result: " << result << std::endl; // prints: cast case 1: input: hello result: hello
}
{
std::string input("hello");
std::string result = static_cast<std::string&&>(input);
std::cout << "cast case 2: input: " << input << " result: " << result << std::endl; // prints: cast case 2: input: result: hello
}
{
std::string input("hello");
static_cast<std::string&&>(input);
std::cout << "cast case 3: input: " << input << std::endl; // prints: cast case 3: input: hello
}
{
std::string input("hello");
std::string&& result = std::move(input);
std::cout << "move case 1: input: " << input << " result: " << result << std::endl;
// prints: move case 1: input: hello result: hello
}
{
std::string input("hello");
std::string result = std::move(input);
std::cout << "move case 2: input: " << input << " result: " << result << std::endl;
// prints: move case 2: input: result: hello
}
{
std::string input("hello");
std::move(input);
std::cout << "move case 3: input: " << input << std::endl;
// prints: move case 3: input: hello
}
}发布于 2019-07-24 17:24:15
至少static_cast和std::move的行为类似,因为std::move确实使用了static_cast
不仅是相似的,而且他们做的事情完全一样。std::move是对rvalue引用的静态强制转换。
有人能解释一下这种行为吗?
result是指input的引用。绑定引用不会修改引用对象。std::string的文档,input对象处于未指定但有效的状态,这可能但与被移动之前没有什么不同。input也不会被修改.https://stackoverflow.com/questions/57187928
复制相似问题