下面的简单代码表明,static_cast 为右值引用类型和 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
}
}
最佳答案
您观察到的行为不足为奇且合情合理。
当你使用
std::string result = static_cast<std::string&&>(input);
调用移动构造函数来初始化result
。移动构造函数移动 input
的内容到result
是有道理的。
对比
std::string&& result = static_cast<std::string&&>(input);
这里,result
不是新对象。它只是 input
的右值引用。这里没有任何内容需要移动 input
的内容。
关于c++ - static_cast 到右值引用和 std::move 在初始化中更改它们的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57187928/