Следующий простой код показывает, что static_cast к ссылочному типу r-value и 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
будет пустым. Вам нужно будет использовать что-то вродеstd::unique_ptr
, чтобы знать наверняка. - person Brian Bi   schedule 24.07.2019