LearnFrenzy
Sign in Take a free test

Move Semantics · Move Semantics Programs · Question 8

Count copies and moves with emplace_back in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Write a Point class that counts constructions, copies and moves, then add points to a reserved vector with push_back of a named object, push_back of a temporary, push_back with std::move, and emplace_back; print the counts.

Solution
main.cpp
#include <iostream>
#include <vector>

struct Point {
    static inline int made = 0, copied = 0, moved = 0;
    double x, y;
    Point(double a, double b) : x(a), y(b) { ++made; }
    Point(const Point& o) : x(o.x), y(o.y) { ++copied; }
    Point(Point&& o) noexcept : x(o.x), y(o.y) { ++moved; }
};

void report(const char* what) {
    std::cout << what << ": made " << Point::made << " copied " << Point::copied << " moved " << Point::moved << '\n';
    Point::made = Point::copied = Point::moved = 0;
}

int main() {
    std::vector<Point> v;
    v.reserve(4);
    Point p(1, 2);
    report("named point");
    v.push_back(p);             report("push_back(p)");
    v.push_back(Point(3, 4));   report("push_back(Point(3,4))");
    v.push_back(std::move(p));  report("push_back(std::move(p))");
    v.emplace_back(5, 6);       report("emplace_back(5,6)");
    return 0;
}

Output Verified by compiling and running

named point: made 1 copied 0 moved 0
push_back(p): made 0 copied 1 moved 0
push_back(Point(3,4)): made 1 copied 0 moved 1
push_back(std::move(p)): made 0 copied 0 moved 1
emplace_back(5,6): made 1 copied 0 moved 0

emplace_back is the only way that constructs exactly once. (For a type of two doubles, copy and move cost the same – the point is to see which constructors run.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links