开发者社区> 问答> 正文

这个代码中,移动构造函数是如何定义的,它做了什么?

这个代码中,移动构造函数是如何定义的,它做了什么?

#include <iostream>
using namespace std;
class BigMemoryPool {    private:        static const int POOL_SIZE = 4096;        int* mPool;
    public:        BigMemoryPool() : mPool(new int[POOL_SIZE]{0}) {            cout << "call default init" << endl;        }
        // 编译器会优化移动构造函数,正常情况可能不会被执行        // 可以添加编译选项 “-fno-elide-constructors” 关闭优化来观察效果        BigMemoryPool(BigMemoryPool && other) noexcept {            mPool = other.mPool;            other.mPool = nullptr;            cout << "call move init" << endl;        }
        BigMemoryPool & operator=(BigMemoryPool && other) noexcept {            if (this != &other) {                this->mPool = other.mPool;                other.mPool = nullptr;            }            cout << "call op move" << endl;            return *this;        }        void showPoolAddr() {            cout << "pool addr:" << &(mPool[0]) << endl;        }
        ~BigMemoryPool() {            cout << "call destructor" << endl;        }};
BigMemoryPool makeBigMemoryPool() {    BigMemoryPool x;  // 调用默认构造函数    x.showPoolAddr();    return x;         // 返回临时变量,属于右值}
int main() {    BigMemoryPool a(makeBigMemoryPool());      a.showPoolAddr();    a = makeBigMemoryPool();      a.showPoolAddr();    return 0;}
// 输出内容call default initpool addr:0x152009600instance addr:0x16fdfeda0pool addr:0x152009600instance addr:0x16fdfeda0  // 编译器优化,这里a和x其实是同一个实例,因此不会触发移动构造call default initpool addr:0x15200e600    // 新的临时变量,堆内存重新分配instance addr:0x16fdfed88  // 临时变量对象地址call op move        // 移动赋值call destructorpool addr:0x15200e600    // a的Pool指向的内存地址变成新临时对象分配的地址,完成转移instance addr:0x16fdfeda0  // a对象的地址没有变化call destructor

展开
收起
三分钟热度的鱼 2024-05-17 14:48:43 40 0
1 条回答
写回答
取消 提交回答
  • 移动构造函数是这样定义的:BigMemoryPool(BigMemoryPool && other) noexcept。它接受一个BigMemoryPool类型的右值引用作为参数。在移动构造函数内部,它将当前对象的mPool指针设置为传入对象的mPool,并将传入对象的mPool设置为nullptr。这样,资源(在这种情况下是内存池)就从传入的对象“移动”到了当前对象,避免了复制大量数据。

    2024-05-17 15:23:38
    赞同 2 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载