Introducing emplacer -- Tim

Another nice way to have a polymorphic collection without sacrificing that performance-precious contiguous memory layout:

Introducing emplacer: allocate subtypes of an abstract base class directly in a container

by Tim

From the article:

So I complained to my friend Jeremy that C++ should be able to do this. This isn't Java, I shouldn't have to do a separate allocation for each object...

As alluded to earlier, you can also use it in containers. Here's an example:

std::vector<ShapeAny> shapes;

shapes.emplace(shapes.end())->emplace<Rect>(3, 4);
shapes.emplace(shapes.end())->emplace<Square>(3);

//emplace returns reference to *this, so you can use it like this too
shapes.push_back(ShapeAny().emplace<Rect>(5, 6));
shapes.push_back(ShapeAny().emplace<Circle>(1));

for (auto shape: shapes) {
  std::cout << shape->area() << std::endl;
}

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.