我对下面的代码有疑问。我的编译器是MSVC++ 17的Visual Studio版本15.3与编译器选项/ STD:C++ 14(与/ STD:C++最新)在释放模式运行:从元组返回元组时复制元组的参数被复制而不是移动
struct Bar
{
int a;
std::string b;
Bar() { std::cout << "default\n"; }
Bar(int a, const std::string& b) : a{ a }, b{ b } { std::cout << "direct\n"; }
Bar(int a, std::string&& b) : a{ a }, b{ std::move(b) } { std::cout << "direct move b\n"; }
Bar(const Bar& other) : a{ other.a }, b{ other.b } { std::cout << "const copy\n"; }
Bar(Bar&& other) : a{ std::move(other.a) }, b{ std::move(other.b) } { std::cout << "move\n"; }
Bar& operator=(const Bar& other)
{
a = other.a;
b = other.b;
std::cout << "const assign\n";
return *this;
}
Bar& operator=(Bar&& other)
{
a = std::move(other.a); //would this even be correct?
b = std::move(other.b);
std::cout << "move assign\n";
return *this;
}
};
std::tuple<Bar, Bar> foo()
{
std::string s = "dsdf";
return { { 1, s }, { 5, "asdf" } };
}
int main()
{
Bar a, b;
std::tie(a, b) = foo();
std::cout << a.a << a.b << std::endl;
std::cout << b.a << b.b;
}
输出是:
default
default
direct
direct move b
const copy <-- Why copy? Why not move>
const copy <-- Why copy? Why not move>
move assign
move assign
1dsdf
5asdf
如果我改变return { { 1, s }, { 5, "asdf" } };
到return { Bar{ 1, s }, Bar{ 5, "asdf" } };
输出变为:
default
default
direct
direct move b
move
move
move assign
move assign
1dsdf
5asdf
问题:为什么在这两种情况下都不行?为什么在第一种情况下调用复制构造函数?