我是靠谱客的博主 传统月光,最近开发中收集的这篇文章主要介绍栈堆的emplace和push_C ++:堆栈的push()与emplace(),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

bd96500e110b49cbb3cd949968f18be7.png

Trying to understand the difference between using push() or emplace() for std::stack.

I was thinking that if I create a std::stack, then I'd use push() because integer is a primitive type and there is nothing for emplace() to construct.

However, if I was creating std::stack then I'd choose emplace() because std::string is an object.

Is this correct usage?

解决方案

To fully understand what emplace_back does, one must first understand variadic templates and rvalue references.

This is a fairly advanced, and deep concept in modern C++. On a map, it would be labeled "there be dragons".

You say that you're new to C++ and trying to learn this stuff. This may not be the answer you might be looking for, but you should skip this detail for now, and come back later after you've wrapped your brain around variadic templates and rvalue references. Then it should all make sense.

But if you insist: for a container containing simple, elementary types like integers, there's little, if any difference. The difference comes when the container's type is some large, sophisticated class, with a complicated constructor, and/or copy-constructor.

The end result of either push or emplace is exactly, 100%, the same. The container gets another element appended to it. The difference is where the element comes from:

1) push takes an existing element, and appends a copy of it to the container. Simple, straightforward. push always takes exactly one argument, the element to copy to the container.

2) emplace creates another instance of the class in the container, that's already appended to the container. The arguments to emplace are forwarded as arguments to the container's class's constructor. Emplace can have either one argument, more than one argument, or no argument at all, if the class has a default constructor.

Note that when the class's constructor takes one argument and it is not marked as explicit, it's possible to abuse push and pass it a constructor argument, instead of an existing instance of the class. But let's pretend that this option does not exist, it often leads to horrible code performance, especially with non-trivial classes.

So: if you want to add a copy of an existing instance of the class to the container, use push. If you want to create a new instance of the class, from scratch, use emplace.

最后

以上就是传统月光为你收集整理的栈堆的emplace和push_C ++:堆栈的push()与emplace()的全部内容,希望文章能够帮你解决栈堆的emplace和push_C ++:堆栈的push()与emplace()所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(43)

评论列表共有 0 条评论

立即
投稿
返回
顶部