首页 > 编程语言 >c++ 使用移动语义来提高 vector 性能

c++ 使用移动语义来提高 vector 性能

时间:2023-08-11 15:24:34浏览次数:46  
标签:25 resource move 语义 c++ length vector include MemoryBlock

本文学习了微软的官方实例,用于理解 std::move 语义。


 
#pragma once
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

class MemoryBlock
{
public:

    // Simple constructor that initializes the resource.
    explicit MemoryBlock(size_t length)
        : _length(length)
        , _data(new int[length])
    {
        std::cout << "In MemoryBlock(size_t). length = "
            << _length << "." << std::endl;
    }

    // Destructor.
    ~MemoryBlock()
    {
        std::cout << "In ~MemoryBlock(). length = "
            << _length << ".";

        if (_data != nullptr)
        {
            std::cout << " Deleting resource.";
            // Delete the resource.
            delete[] _data;
        }

        std::cout << std::endl;
    }

    // Copy constructor.
    MemoryBlock(const MemoryBlock& other)
        : _length(other._length)
        , _data(new int[other._length])
    {
        std::cout << "In MemoryBlock(const MemoryBlock&). length = "
            << other._length << ". Copying resource." << std::endl;

        std::copy(other._data, other._data + _length, _data);
    }

    // Copy assignment operator.
    MemoryBlock& operator=(const MemoryBlock& other)
    {
        std::cout << "In operator=(const MemoryBlock&). length = "
            << other._length << ". Copying resource." << std::endl;

        if (this != &other)
        {
            // Free the existing resource.
            delete[] _data;

            _length = other._length;
            _data = new int[_length];
            std::copy(other._data, other._data + _length, _data);
        }
        return *this;
    }

    // Retrieves the length of the data resource.
    size_t Length() const
    {
        return _length;
    }

    // Move constructor.
    MemoryBlock(MemoryBlock&& other) noexcept
        : _data(nullptr)
        , _length(0)
    {
        std::cout << "In MemoryBlock(MemoryBlock&&). length = "
            << other._length << ". Moving resource." << std::endl;

        //// Copy the data pointer and its length from the
        //// source object.
        //_data = other._data;
        //_length = other._length;

        //// Release the data pointer from the source object so that
        //// the destructor does not free the memory multiple times.
        //other._data = nullptr;
        //other._length = 0;

        *this = std::move(other);

    }

    // Move assignment operator.
    MemoryBlock& operator=(MemoryBlock&& other) noexcept
    {
        std::cout << "In operator=(MemoryBlock&&). length = "
            << other._length << "." << std::endl;

        if (this != &other)
        {
            // Free the existing resource.
            delete[] _data;

            // Copy the data pointer and its length from the
            // source object.
            _data = other._data;
            _length = other._length;

            // Release the data pointer from the source object so that
            // the destructor does not free the memory multiple times.
            other._data = nullptr;
            other._length = 0;
        }
        return *this;
    }

private:
    size_t _length; // The length of the resource.
    int* _data; // The resource.
};


int main()
{
    // Create a vector object and add a few elements to it.
    vector<MemoryBlock> v;
    v.push_back(MemoryBlock(25));
    //v.push_back(MemoryBlock(75));

    // Insert a new element into the second position of the vector.
    //v.insert(v.begin() + 1, MemoryBlock(50));
}

运行结果:

In MemoryBlock(size_t). length = 25.
In MemoryBlock(MemoryBlock&&). length = 25. Moving resource.
In operator=(MemoryBlock&&). length = 25.
In ~MemoryBlock(). length = 0.
In ~MemoryBlock(). length = 25. Deleting resource.

从输出可以看出,MemoryBlock仅仅初始化了一次,没有调用 Copy constructor 和 Copy assignment operator,只是调用了 Move constructor。而且,在最终释放资源时也没有出现内存的二次释放问题。

参考:https://learn.microsoft.com/en-us/cpp/cpp/move-constructors-and-move-assignment-operators-cpp?view=msvc-170

标签:25,resource,move,语义,c++,length,vector,include,MemoryBlock
From: https://www.cnblogs.com/itfanr/p/17623046.html

相关文章

  • C++调用Python传入参数、图片并接受返回值
    最近在做C++调用Pytorch模型进行识别的任务,C++关于Pytorch的教程很少,基本上都是用Python写的,但因为要识别任务是实时的,Python的执行效率不如C++,所以主题代码还是没用Python。网上利用C++调用Pytorch模型的方法主要是把模型文件转化成C++可以加载和执行的模型文件,利用的是TorchS......
  • C++ #pragma once指令:保护C++头文件不被重复包含
    一、#ifndef/#define/#endif指令的问题在C++中,头文件的作用就是将代码以模块的形式组织起来,便于复用和维护。但是,头文件很容易出现重复定义的问题。比如,某个头文件被多个源文件包含,这些源文件又有可能被其他源文件包含,那么就有可能出现一个头文件被重复包含的情况。这样就会......
  • C++多线程不加锁操作同一个整数
    #include<iostream>#include<thread>#include<vector>#include<chrono>#include<atomic>usingnamespacestd;intnum=0;//volatileintnum=0;//atomic<int>num=0;voidadd(){inttimes=0;for(int......
  • VS2019 C++ 调用python函数/类对象的方法
    1.环境配置VS工程配置要和python一致,安装的python如果是64位的,工程配置也要选成64位的在工程配置中添加包含目录和库目录,添加python环境目录里的include和libs文件夹路径。想要运行的keras-yolo3是在Anaconda中配置的环境,所以相应的文件夹路径可以在Anaconda的环境文件中......
  • 软件开发入门教程网 Search之C++ 动态内存
       C++基本的输入输出   ......
  • 软件开发入门教程网 Search之C++ 环境设置
       C++基本的输入输出   ......
  • C++ Boost库简介
    1、boost是一个功能强大、构造精良、跨平台、代码开源、完全免费的c++程序库。1)功能强大:共包含160余个库/组件,涵盖字符串与文本处理、容器、迭代器、算法、图像处理、模板元编程、并发编程等多个领域。2)构造精良: 由c++标准委员会成员发起倡议并建立boost社区,C+......
  • C++ Boost库介绍
    Boost库是C++的一个开源类库,包含了大量实用工具和组件,可以大大简化C++编程过程中的繁琐操作。以下是Boost库常见的运用场景:1.多线程编程:Boost.Thread模块提供了丰富的线程相关功能,如锁、条件变量、线程池等,使得多线程编程更加容易。2.正则表达式处理:Boost.Regex模块提供了对正......
  • C++ 构造函数初始化:提高代码可读性和执行效率
    在C++中,构造函数是用来初始化对象数据成员的。一个对象在创建的时候,构造函数会被自动调用,以便为该对象的数据成员赋初值。传统的初始化方式是在构造函数内部对数据成员逐一进行初始化,这种方式虽然可行,但是代码复杂度高且效率低下。本文将介绍如何使用构造函数初始化列表来提高......
  • C/C++住院病人管理系统[2023-08-11]
    C/C++住院病人管理系统[2023-08-11]22、住院病人管理系统(难度等级8)使用C或C++,选择一种计算机编程软件和数据库管理系统来实现一个住院病人管理系统。系统需要实现的功能如下:(1)添加、删除和修改病人信息:向系统中添加、删除和修改仓库信息,信息包括(住院号、姓名、年龄、住院时间、......