Avoiding copy constructor during populating member vector

Viewed 550

I have an class A:

class A {
  int value1;
  int value2;
  std::string text;

public:
  A(int value1, int value2, std::string text) 
   : value1(value1), value2(value2), text(text) { }
};

And some "container" class B:

class B {
  std::vector<A> objects;
  ...

public:
  ...
  void addObject(A a) {
    objects.push_back(a);
  }
};

And code:

B b;
A a(2, 5, "test");
b.addObject(a);
//I no longer need a from now on

My problem is, how to optimize B::addObject(A a) to avoid any copying. What I want to achive is to add new object of type A to B.objects via B's method.

2 Answers

There are many answers to this question. You could just change your B function to move(), and move() into that function:

void addObject(A a) { objects.push_back(std::move(a)); }

b.addObject(std::move(a)); // two moves

You could add overloads of addObject that take by const lvalue reference and by rvalue reference

void addObject(A const& a) { objects.push_back(a); }
void addObject(A&& a) { objects.push_back(std::move(a)); }

b.addObject(std::move(a)); // one move

You could add a function template for addObject that emplaces:

template <class... Args>
void addObject(Args&&... args) { objects.emplace_back(std::forward<Args>(args)...); }

b.addObject(2, 5, "test"); // zero moves

Either way, there's a completely unnecessary copy here:

A(int value1, int value2, std::string text) 
: value1(value1), value2(value2), text(text) { }

you want:

A(int value1, int value2, std::string text) 
: value1(value1), value2(value2), text(std::move(text)) { }

You might change the parameter type of addObject and use emplace_back, to avoid constructing an object of A which won't be used later and copying it into the vector. e.g.

void addObject(int value1, int value2, std::string text) {
  objects.emplace_back(value1, value2, text);
}

and

B b;
b.addObject(2, 5, "test"); // construct the element directly into the vector without constructing A
Related