简体   繁体   中英

How does `emplace_back` in an `std::vector` work?

I noticed that emplace_back in an std::vector changes the address of previous vector elements. Why?

From the backing storage perspective whether you push or emplace doesn't matter. The difference there is for the argument.

Therefore the usual relocation mechanism are in place. They will move the elements when currently allocated contiguous storage is exhausted.

The rules for iterator invalidation stay the same. Checkout " Iterator invalidation " on http://en.cppreference.com/w/cpp/container/vector .

不幸的是,这是标准的:如果新的size()大于Capacity(),则所有迭代器和引用均无效。

If the current capacity of the backing store for the vector cannot accommodate a new element then a new, larger backing store must be allocated, all the existing elements moved to it, then the new element can be constructed in place.

Using emplace_back() doesn't change the fact that the backing store has to be large enough to fit the new element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM