10.9:C++移动语义的性能和效率分析!(课程共6350字,2个代码举例)

本文深入探讨C++11引入的移动语义,通过使用智能指针、std::vector和std::move等,避免不必要的对象拷贝和移动,提升程序性能。文章通过实例分析移动构造函数和移动赋值运算符的使用,强调正确处理资源所有权以避免内存问题,以及在使用std::vector时避免空间浪费。同时,文章提醒开发者注意移动语义的适用场景和潜在细节问题,以实现更高效、可维护的代码。
摘要由CSDN通过智能技术生成

② 使用std::vector实现移动语义

std::vector是C++中常用的动态数组容器,可以存储任意类型的数据,具有高度的可扩展性和灵活性。在实现移动语义时,我们可以使用std::vector来避免不必要的对象拷贝和移动。下面是一个使用std::vector实现移动语义的例子:


#include <iostream>
#include <memory>

class MyClass {
public:
    MyClass(int size) : size_(size) {
        data_ = new int[size_];
        for (int i = 0; i < size_; i++) {
            data_[i] = i;
        }
        std::cout << "Constructor called." << std::endl;
    }

    MyClass(const MyClass& other) : size_(other.size_) {
        data_ = new int[size_];
        for (int i = 0; i < size_; i++) {
            data_[i] = other.data_[i];
        }
        std::cout << "Copy constructor called." << std::endl;
    }

    MyClass(MyClass&& other) noexcept : size_(other.size_), data_(other.data_) {
        other.size_ = 0;
        other.data_ = nullptr;
        std::cout << "Move constructor called." << std::endl;
    }

    ~MyClass() {
        delete[] data_;
        std::cout << "Destructor called." << std::endl;
    }

    MyClass& operator=(const MyClass& other) {
        if (this != &other) {
            delete[] data_;
            size_ = other.size_;
            data_ = new int[size_];
            for (int i = 0; i < size_; i++) {
                data_[i] = other.data_[i];
            }
        }
        std::cout << "Copy assignment operator called." << std::endl;
        return *this;
    }

    MyClass& operator=(MyClass&& other) noexcept {
        if (this != &other) {
            delete[] data_;
            size_ = other.size_;
            data_ = other.data_;
            other.size_ = 0;
            other.data_ = nullptr;
        }
        std::cout << "Move assignment operator called." << std::endl;
        return *this;
    }

private:
    int size_;
    int* data_;
};

int main() {
    auto ptr1 = std::make_unique<MyClass>(10);
    auto ptr2 = std::move(ptr1);
    return 0;
}

在上面的例子中,我们使用std::make_unique创建了一个std::unique_ptr对象ptr1,并将其移动到ptr2中。这样可以避免不必要的对象拷贝和移动,提高程序的性能和可维护性。

🌷🌷🌷🌷课程概述(课程共6350字,2个代码举例)

🌷🌷🌷🌷C++移动语义的性能和效率分析:

🌷🌷🌷🌷在使用移动语义时,我们需要注意一些细节问题,例如:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小兔子平安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值