MST

星途 面试题库

面试题:C++ 移动语义在容器插入操作中的优势

在C++ 中,当向容器(如std::vector)插入元素时,移动语义是如何发挥作用的?请举例说明使用移动语义相较于拷贝语义,在插入操作上有哪些优势。
21.4万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

移动语义在向 std::vector 插入元素时的作用

在C++ 中,当向 std::vector 插入元素时,移动语义允许在不进行深拷贝的情况下,将资源的所有权从一个对象转移到另一个对象。当插入一个右值(例如临时对象)时,std::vector 会使用移动构造函数来获取该对象的资源,而不是复制这些资源。

示例代码

#include <iostream>
#include <vector>
#include <string>

class MyClass {
public:
    MyClass() : data(new int[1000]) {
        std::cout << "Constructor: " << this << std::endl;
    }

    MyClass(const MyClass& other) : data(new int[1000]) {
        std::copy(other.data, other.data + 1000, data);
        std::cout << "Copy Constructor: " << this << std::endl;
    }

    MyClass(MyClass&& other) noexcept : data(other.data) {
        other.data = nullptr;
        std::cout << "Move Constructor: " << this << std::endl;
    }

    ~MyClass() {
        delete[] data;
        std::cout << "Destructor: " << this << std::endl;
    }

private:
    int* data;
};

int main() {
    std::vector<MyClass> vec;
    // 插入临时对象,会调用移动构造函数
    vec.push_back(MyClass());

    return 0;
}

移动语义相较于拷贝语义在插入操作上的优势

  1. 性能提升:移动语义避免了深拷贝操作,对于包含大量数据的对象,深拷贝开销很大。移动语义只是转移资源的所有权,通常是几个指针操作,性能显著提高。例如上述 MyClass 类,拷贝构造函数需要复制1000个 int,而移动构造函数只是转移指针。
  2. 减少内存分配:拷贝语义可能需要为新对象分配内存,然后复制数据。移动语义则不需要额外的内存分配,直接使用源对象已分配的内存,从而减少了内存碎片和内存分配开销。