classA{public:explicitA(intx){}};vectorv;v.push_back(1);//compilererrorsincenoimplicitconstructorv.emplace_back(1);//callsexplicitconstructor以上来自video大卫·斯通。我不明白的是为什么emplace_back调用显式构造函数?我在C++标准中看不到任何内容使这合法。只有在听了DavidStone的youtube视频后,我发现了这件事。现在,我对std::map进行同样的尝试。mapm;m.insert(pair(1,2));//compile
根据emplace_back的定义,voidemplace_back(Args&&...args);是一个可变模板函数。所以,我写了以下内容:#includeintmain(){std::vectormyvector2(10,0);myvector2.emplace_back(1,2,3,4,5,6);}编译器提示:g++-std=c++0xstlstudy.cc‘Internalcompilererror:Errorreportingroutinesre-entered.Pleasesubmitafullbugreport,withpreprocessedsourceifapprop
我使用的是C++11和gcc-4.7.0。我正在寻找STL解决方案。我想要一个未排序的multimap,其中包含以短字符串作为键的myClass对象。Emplace看起来是一种在我构建对象时将对象放入map的好方法,但我不确定它是否可以这样做,或者它是否只会构建键/对象对。这应该是有效的:table.emplace(myKey,myClass(arg1,arg2,arg3));但是执行以下操作会更有效率吗,它甚至是有效代码吗?table.emplace(myKey,arg1,arg2,arg3); 最佳答案 根据this,gcc-4
以下代码对push_back失败,对emplace_back成功:#includevolatileintx=0;intmain(){std::vectorvec;vec.emplace_back(x);vec.push_back(x);//error:nomatchingfunctionforcallto'std::vector::push_back(volatileint&)'}我知道push_back失败是因为它需要一个引用并试图从该引用中隐式地丢弃volatile限定符。然而,emplace_back也接受一个引用(右值引用是引用)。为什么区别对待?
在我的C++应用程序中,我大量使用像vector这样的STL容器。对push_back的调用很多,我一直担心不必要的构造和复制操作。我的应用程序非常低级,我非常关心CPU和内存使用情况。我是否应该将所有对push_back的调用替换为对emplace_back的调用?我正在使用VisualStudio2013。 最佳答案 我将对push_back的所有调用替换为对emplace_back的调用,并注意到以下内容:RAM使用量减少了大约20%(更新:这可能是由于其他影响)CPU使用率没有变化二进制文件稍小(x64)没有兼容性问题根据这
为什么这段代码无法编译?std::map>m;m.emplace(1,1,1);假设我们可以编辑std::map::emplace的代码,是否可以更改它以使之前的代码有效? 最佳答案 无效的原因与无效的原因完全相同:std::pair>p{1,1,1};因为上面本质上就是map的emplace归结为。要使其正常工作,您可以使用piecewise_constructconstructorofstd::pair,正是为了这个目的而引入的:m.emplace(std::piecewise_construct,std::forward_as
我有以下旨在创建数组的代码,但没有默认初始化其对象。我想完美地转发到placementnew,这似乎发生了,但我发现对象的析构函数在emplace函数中被调用。#include#include//std::uninitialized_copy,std::allocator...#include//std::move...#includestructInt{inti;Int():i(-1){std::coutclassNoInitArray{std::bitsetm_used;T*m_array=reinterpret_cast(::operatornew(sizeof(T)*S));p
如果我有课classfoo{public:foo(){//spendsometimeanddosomething.}private://somedatahere}现在我有一个foo的vector,我想把这个vector放到另一个vector中vectorinput;//assumeithas5elementsvectoroutput;这两条线有任何性能差异吗?output.push_back(input[0])output.emplace_back(input[0]) 最佳答案 IsthereANYperformancediffer
我想知道是否可以使用emplace_back将项目存储到vector中,emplace_back是一种派生自vector所期望的类的类型。例如:structfruit{std::stringname;std::stringcolor;};structapple:fruit{apple():fruit("Apple","Red"){}};其他地方:std::vectorfruits;我想在vector中存储一个apple类型的对象。这可能吗? 最佳答案 没有。vector仅存储固定类型的元素。你想要一个指向对象的指针:#include
vector工作正常Headerstd::vector>subnodes_m;DefinitionvoidCompositeSceneNode::AddChild(SceneNode*subnode_p){subnodes_m.emplace_back(subnode_p);}multimap没有Headerstd::multimap>subnodes_m;DefinitionvoidCompositeSceneNode::AddChild(SceneNode*subnode_p,unsignedintlayerIndex){subnodes_m.emplace(layerIndex,