LoginSignup
4
6

More than 5 years have passed since last update.

Emplacementについて

Last updated at Posted at 2014-08-13

概要

STLのコンテナで要素を追加する時にC++11からemplacementというものを使うことで、オブジェクトの無駄な生成と破棄を防ぐことができるということを知ったので少しだけ試してみました。

std::vectorを使って検証

Person.h
class Person
{
public:
  Person(int age, const std::string& name);
  Person(const Person& other);
  ~Person();

private:
  int age;
  std::string name;
};
Person.cpp
Person::Person(int age, const std::string& name)
{
  std::cout << "Constructor is called." << std::endl;
  this->age = age;
  this->name = name;
}

Person::Person(const Person& other)
{
  std::cout << "Copy Constructor is called." << std::endl;
  this->age = other.age;
  this->name = other.name;
}

Person::~Person()
{
  std::cout << "Destructor is called." << std::endl;
}

簡単なPersonクラスを使ってオブジェクトの生成と、std::vectorへの要素の追加を試してみます。とりあえず、push_backとemplace_back, insertとemplaceで調べてみます。

main.cpp
int main(int argc, const char *argv[])
{
  std::vector<Person> vec;

  std::cout << "------------ push_back ---------------" << std::endl;
  vec.push_back({15, "Yumi"});
  vec.clear();

  std::cout << "------------ emplace_back ---------------" << std::endl;
  vec.emplace_back(16, "Mark");
  vec.clear();

  std::cout << "------------ insert ---------------" << std::endl;
  vec.insert(vec.begin(), {20, "Taro"});
  vec.clear();

  std::cout << "------------ emplace ---------------" << std::endl;
  vec.emplace(vec.begin(), 24, "Green");
  vec.clear();
}
Result
------------ push_back ---------------
Constructor is called.
Copy Constructor is called.
Destructor is called.
Destructor is called.
------------ emplace_back ---------------
Constructor is called.
Destructor is called.
------------ insert ---------------
Constructor is called.
Copy Constructor is called.
Destructor is called.
Destructor is called.
------------ emplace ---------------
Constructor is called.
Destructor is called.

結果を見てみるとEmplacementを使った方は使ってない方と比べて、オブジェクトのコピーと破棄が一回ずつ少ないことが確認できました。

まとめ

単純な検証ではありましたが、ドキュメントを読んでよくわからなかったので実際に動かしてみて確認すること理解が深まりました。今まではpush_backしか使ったことがなかったので使える場面ではemplaceを使っていきたいと思います。

参考文献

Placement Insert
cpprefjp

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6