Does std :: move enable lvalue links? How does std :: move work on standard containers?

#include <vector>

struct A { int a[100]; };

void foo (const A& a) {
  std::vector<A> vA; 
  vA.push_back(std::move(a));  // how does move really happen?
}

int main () {
  A a;
  foo(a);
}

The above code compiles in order. Now everywhere it is written that moveavoids copying.
Following are my inquiries:

  • Does it really work movewhen it comes to lvalue [non] - constlink?
  • Even with the "rvalue reference", how to avoid copying when an object is inserted into a standard container, as described above?

eg.

void foo (A&& a) {  // suppose we invoke this version
  std::vector<A> vA; 
  vA.push_back(std::move(a));  // how copy is avoided?
}
+4
source share
2 answers

std::move . lvalue rvalue. const A && (, , ).

std::vector a const A & a A &&, const A &, const A && const A &

, const, / , - . ( , , )

A. A POD, , / A.

, , , reset 0. , , .

+8

, . , .

#include <vector>
#include <iostream>

struct A { 
  int a[100];
  A() {}
  A(const A& other) {
    std::cout << "copy" << std::endl;
  }
  A(A&& other) {
    std::cout << "move" << std::endl;
  }
};

void foo(const A& a) {
  std::vector<A> vA; 
  vA.push_back(std::move(a));
}

void bar(A&& a) {
  std::vector<A> vA; 
  vA.push_back(std::move(a));
}

int main () {
  A a;
  foo(a);            // "copy"
  bar(std::move(a)); // "move"
}
0

Source: https://habr.com/ru/post/1651063/


All Articles