如何实现大型非指针成员的移动构造函数

How to implement move constructor for large size non-pointer member?

本文关键字:成员 指针 移动 构造函数 大型 何实现 实现      更新时间:2023-10-16

在这个网站上有一个带有move构造函数的简单类的例子。

类似类的move构造函数看起来怎么样:

class MemoryPage
{
        std::vector<char> buff;
        public:
        explicit MemoryPage(int sz=512)
        {
                for(size_t i=0;i<sz;i++)
                        buff.push_back(i);
        }
};

会是吗

MemoryPage::MemoryPage(MemoryPage &&other)
{
        this->buff = std::move(other.buff);
}

一个兼容的C++11编译器将自动为您创建一个移动构造函数(Visual Studio 2013没有)。默认的移动构造函数将执行成员移动,std::vector实现移动语义,因此它应该执行您想要的操作。

但是,是的,如果出于某种原因,您确实需要自己定义看起来正确的move构造函数。尽管最好使用构造函数初始化列表并声明它noexcept:

MemoryPage::MemoryPage(MemoryPage &&other) noexcept : buff(std::move(other.buff)) { }