提问人:KcFnMi 提问时间:10/6/2022 更新时间:10/6/2022 访问量:103
移动构造函数实际上不是在 Microsoft 的示例中调用的?
The move constructor is not actually called on Microsoft's example?
问:
生成并运行来自 Microsoft 的 Move 构造函数示例,输出为:
default
copy
int,int,int
b2 contents: Toupee Megaphone Suit
但是,我预计它会在某个时候打印出来。移动构造函数是否实际被调用?为什么没有印刷品?move
以下是引用链接中的代码:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Box {
public:
Box() { std::cout << "default" << std::endl; }
Box(int width, int height, int length)
: m_width(width), m_height(height), m_length(length)
{
std::cout << "int,int,int" << std::endl;
}
Box(Box& other)
: m_width(other.m_width), m_height(other.m_height), m_length(other.m_length)
{
std::cout << "copy" << std::endl;
}
Box(Box&& other) : m_width(other.m_width), m_height(other.m_height), m_length(other.m_length)
{
m_contents = std::move(other.m_contents);
std::cout << "move" << std::endl;
}
int Volume() { return m_width * m_height * m_length; }
void Add_Item(string item) { m_contents.push_back(item); }
void Print_Contents()
{
for (const auto& item : m_contents)
{
cout << item << " ";
}
}
private:
int m_width{ 0 };
int m_height{ 0 };
int m_length{ 0 };
vector<string> m_contents;
};
Box get_Box()
{
Box b(5, 10, 18); // "int,int,int"
b.Add_Item("Toupee");
b.Add_Item("Megaphone");
b.Add_Item("Suit");
return b;
}
int main()
{
Box b; // "default"
Box b1(b); // "copy"
Box b2(get_Box()); // "move"
cout << "b2 contents: ";
b2.Print_Contents(); // Prove that we have all the values
char ch;
cin >> ch; // keep window open
return 0;
}
答:
2赞
Crafty-Codes
10/6/2022
#1
如果要查看 Move 构造函数,请在下面添加某处,它将调用 Move 构造函数。我只会在谷歌上搜索“五 cpp 法则”,因为还有复制和移动赋值运算符。Box b3(std::move(b));
评论
0赞
KcFnMi
10/6/2022
好吧,被明确调用,所以是的,我可以理解后面的内容。std::move
0赞
KcFnMi
10/6/2022
在哪些情况下隐式调用移动构造函数?
0赞
Crafty-Codes
10/7/2022
基本上只有当你做 std::move 时。有一些例外,比如它是否是唯一存在的构造函数。编辑:文档用于在“解释”下移动,然后初始化@KcFnMi也发现了这个 stackOverflow
评论
Box b2(get_Box());