移动构造函数实际上不是在 Microsoft 的示例中调用的?

The move constructor is not actually called on Microsoft's example?

提问人:KcFnMi 提问时间:10/6/2022 更新时间:10/6/2022 访问量:103

问:

生成并运行来自 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;
}
C++ 复制构造函数 move-semantics

评论

3赞 molbdnilo 10/6/2022
像所有免费介绍一样,MIcrosoft的“学习C++”材料不是很好。其中很多似乎是由根本不使用 C++ 的人编写的(其中一些是完全错误的)。取而代之的是一本好书
1赞 WhozCraig 10/6/2022
你可能会觉得很有趣。基本上,在您询问的情况下,复制和移动都被省略了。
0赞 KcFnMi 10/6/2022
这个被省略的东西对我来说有点陌生。我可以说,在,移动,然后应该发生副本,但由于这个省略的事情,它们实际上被跳过了吗?Box b2(get_Box());
0赞 BoP 10/6/2022
“因为这个省略的东西,他们居然被跳过了?”是的,正是如此。
1赞 BoP 10/6/2022
另请注意页面顶部提到的“13 位贡献者”。这使得材料有点随机的噪声。

答:

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