【发布时间】:2018-01-23 11:24:24
【问题描述】:
我对以下代码有疑问。我的编译器是 MSVC++ 17 Visual Studio 版本 15.3,编译器选项 /std:c++14(相对于 /std:c++latest)在发布模式下运行:
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
问题:为什么在这两种情况下都不执行移动?为什么第一种情况会调用拷贝构造函数?
【问题讨论】:
标签: c++ visual-c++ c++14 visual-studio-2017 move-semantics