为了减少输入类似内容的简单原因:std::shared_ptr;std::unique_ptr;每次想使用智能指针的时候,我就想到了使用模板别名:templateusingsptr=std::shared_ptr;templateusinguptr=std::unique_ptr;所以我可以像这样使用它们:sptr;uptr;假设我在自己的命名空间中保护它们,以这种方式使用带有shared/unique_ptr的模板别名是否有任何陷阱或限制?我会不会做一些我可以用直接模板语法做而我不能用别名做的事情?由于其他原因,这是一个坏主意吗? 最佳答案
这是一个与此post类似的问题.我认为最有前途的答案与模板化静态初始化有关。这是该答案的类(class):templateclasscreate_map{private:std::mapm_map;public:create_map(constT&key,constU&val){m_map[key]=val;}create_map&operator()(constT&key,constU&val){m_map[key]=val;return*this;}operatorstd::map(){returnm_map;}};用法:std::mapmymap=create_map(1,2)(
我目前正在学习C++并专注于STL。我没有找到这个问题的答案,所以问题来了:如何在数据结构中设置元素map>>?以下带有一些注释的代码说明了这个问题:#include#include#include#includeusingnamespacestd;//UsedintheexamplestructResource{};intmain(intargc,char**argv){//Iwasabletogetthefollowingmaprunningfine//int->{string->unique_ptr}map>>data;map>toBeInserted;toBeInserted[
如何在一行中正确调整unique_ptrvector的大小而不gcc给出有关已删除函数的编译错误?vector>>a;a.resize(.....)更新:这是我使用的代码,可以正常工作。intwidth,height;vector>>a;a.resize(width);for(inti=0;i如果可能的话,我想一次调整大小,就像调整vector的vector的大小一样;vector>intObj;intObj.resize(width,vector(height,int()));但每当我尝试使用以下方法调整上述vector的大小时,我都会收到此错误;a.resize(x,vector>
有一个不错的小技巧here允许使用std::unique_ptr不完整的类型。相关代码如下://File:erasedptr.h#include#include//typeeraseddeletor(animplementationtypeusing"veneer")templatestructErasedDeleter:std::function{ErasedDeleter():std::function([](T*p){deletep;}){}};//Aunique_ptrtypedeftemplateusingErasedPtr=std::unique_ptr>;//Declar
我对异步编程不是很熟悉,我有一个问题。我的问题如下。给定boost.asio中C++11的echo_server示例:http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/example/cpp11/spawn/echo_server.cpp我想知道std::make_shared可以在C++14中替换为std::unique_ptr在C++14中,避免了引用计数的开销。我不确定,因为我们有shared_from_this()但不是像unique_from_this()这样的东西,那么我怎样才能访问unique_ptr从里面t
我正在查看companioncode的"HourglassAPI"talkCppCon2014的主要内容是通过使用具有C签名的函数包装类的成员函数来为C++库提供CAPI。除其他外,我对对象的构造方式很感兴趣。在构造新的hairpoll对象的函数hairpoll_construct中,通过获取指针std::make_unique(person).release()实际上是在处理异常的函数中调用的。一个更简单的方法是求助于一个普通的newhairpoll(person)哪些场景更适合前者?这是否与这个特殊API的工作方式有关,还是比这更通用? 最佳答案
我正在寻找一种方法来使用unique_ptr来分配一个结构,该结构包含一个char数组,其中包含动态设置的字节数以支持不同类型的消息。假设:structMyMessage{uint32_tid;uint32_tdata_size;chardata[4];};如何将下面的send_message()转换为使用智能指针?voidsend_message(void*data,constsize_tdata_size){constautomessage_size=sizeof(MyMessage)-4+data_size;constautomsg=reinterpret_cast(newcha
为什么要在VS2017中编译?#include#includeusingnamespacestd;structx{x(){coutvoidfoo(T&&item){structboo{Titem;boo(T&&t):item(std::move(t)){}};newboo(std::move(item));}intmain(){std::unique_ptrb(newx);foo(b);//IwouldexpectthatIshouldputstd::move(b)here.}按照编写的代码,输出是x()~x()如果foo(b)行写为foo(std::move(b)),那么输出就是x(
从C++17开始,您可以使用make_unique为了创建指向数组的智能指针,例如:unique_ptrptr=make_unique(10);这将创建一个指向10个元素数组的智能指针(将调用适当的deleter[]的事实也很棒)。但是根据thismake_shared不支持此类功能(至少在C++17中不支持,据我所知):shared_ptrptr=make_shared(10);上面的代码显然是非法的。事实上,我的VisualStudio2017(v141)吐出以下错误:C2070:'int[]':illegalsizeofoperand'有趣的是shared_ptr本身确实支持数组