Processing when std::vector element position changes

Brief introduction

  • When push_back, insert, reserve, resize and other functions cause memory reallocation, or when insert and erase cause the position of the element to move, vector will try to "move" the element to a new memory area. Vector usually guarantees strong exception safety. If the element type does not provide a move constructor that guarantees no exceptions, vector usually uses a copy constructor.

demo

//
//  main.cpp
//
//  Created by wz on 2020/12/27.
//

#include <iostream>
#include <vector>

using namespace std;

class A {
    
    
public:
  A()
  {
    
    
    cout << "A()\n";
  }
  A(const A&)
  {
    
    
    cout << "A(const A&)\n";
  }
  A(A&&)
  {
    
    
    cout << "A(A&&)\n";
  }
};

class B {
    
    
public:
  B()
  {
    
    
    cout << "B()\n";
  }
  B(const B&)
  {
    
    
    cout << "B(const B&)\n";
  }
  B(B&&) noexcept  // A B差别在这里
  {
    
    
    cout << "B(B&&)\n";
  }
};

int main()
{
    
    
    {
    
    
        vector<A> v1;
        v1.emplace_back();
        v1.emplace_back();
        v1.emplace_back();
    }
    cout << "*************************" << endl;
    {
    
    
        vector<B> v2;
        v2.emplace_back();
        v2.emplace_back();
        v2.emplace_back();
    }

    return 0;
}
  • result
A()
A()
A(const A&)
A()
A(const A&)
A(const A&)
*************************
B()
B()
B(B&&)
B()
B(B&&)
B(B&&)

Guess you like

Origin blog.csdn.net/luoshabugui/article/details/111828621