我想知道在C++中是否有合理的理由通过引用返回唯一指针,即std::unique_ptr&?我以前从未真正见过这种技巧,但我的新项目似乎经常使用这种模式。乍一看,它只是有效地打破/规避了“唯一所有权”契约,使得无法在编译时捕获错误。考虑以下示例:classTmContainer{public:TmContainer(){//Createsomesortofcomplexobjectonheapandstoreunique_ptrtoitm_time=std::unique_ptr(newtm());//Storesomethingmeaningfulinitsfieldsm_time-
Here是来自gcc的测试文件,livedemostructdo_nothing{templatevoidoperator()(T*){}};intmain(){inti=0;std::unique_ptrp1(&i);std::unique_ptrp2;static_assert(!std::is_assignable::value,"");//note!here.}std::is_assignableIftheexpressionstd::declval()=std::declval()iswell-formedinunevaluatedcontext,providesthemem
所以我有一个像这样的vector:std::vector>myVector;然后我有另一个vector,其中包含SomeClass的原始指针:std::vectormyOtherVector;如果myOtherVector中有一个元素,它也会在myVector中,所以我想遍历myOtherVector中的每个元素并删除来自myVector的相同元素。然后清除vector。这是我想出的:for(size_ti=0;i这会产生编译时错误,因为myVector拥有唯一的指针,但我给remove()函数一个原始指针。这是我需要帮助的地方,因为我不知道解决这个问题的正确方法是什么。我将行更改为:
移动unique_ptr的最佳成语是什么?到unique_ptr?用例:假设您在某个缓冲区中创建了一个C字符串。为确保在出现异常时进行正确清理,可以使用unique_ptr引用该缓冲区.构造字符串后,您可能希望将其移动到某个类成员,声明为unique_ptr。以避免进一步修改字符串。这是我迄今为止最好的:std::unique_ptrres;std::unique_ptrbuf(newchar[4]);buf[0]='f';buf[1]=buf[2]='o';buf[3]='\0';res=std::unique_ptr(const_cast(buf.release()));单纯的移动
std::promisep1;autof=p1.get_future();{std::promisep2(std::move(pr));}boolvalid=f.valid();//truef.wait();//doesnotthrow,orfail,butreturnsimmediatelyf.get();//throwsanexception有什么方法可以在调用get之前检查future是否会抛出异常?我希望valid会检查...我不太确定如何让valid返回false。在不设置值的情况下销毁promise不会这样做。 最佳答案
std::unique_ptrp(newint[10]);//okstd::shared_ptrp(newint[10]);//Errorshared_ptrsp(newint[10],[](int*p){delete[]p;});//Ok,writingcustomdeleterfor//arraysinceshared_ptrwillcall//deletebydefault.与unique_ptr相比,数组的shared_ptr签名有什么不同的具体原因吗?如果两个api都遵循类似的签名,那就更简单了。 最佳答案 unique_
TL;DR是VS2013的优化器混淆了,还是我的测量有误,或者全局虚拟变量实际上是否需要可变才能使测试有效或____?免责声明:这主要是出于“学术”兴趣,我不认为我看到的差异会真正影响任何生产代码。简介:我最近的一些测量让我找到了thisquestion因为我发现std::vector>之间存在显着差异和boost::ptr_vector在VS2013上。(另见评论there)看来,对于我的特定测试用例,访问boost::ptr_vector中的元素比使用unique_ptrvector快50%!我的测试代码在这里:http://coliru.stacked-crooked.com/a
voidsss(boost::promise&res){res.set_value("hi");}voidyyy(boost::promise&res){res.set_value("hello");}intmain(){boost::threadth;boost::promisea;th=boost::thread(sss,boost::ref(a));th.join();std::cout我收到promise已经满足的错误。如何复用同一个Promise对象? 最佳答案 用未使用的promise替换它:a=boost::promi
我的做法是:classSomeClass{std::vector>myObjects;public:voidtakeOwnership(MyObject*nowItsReallyMyObject){myObjects.emplace_back(std::move(nowItsReallyMyObject));}};我做的每件事都正确吗?有没有更好的解决方案? 最佳答案 move是多余的。我自己,我会这样做:voidtakeOwnership(std::unique_ptrnowItsReallyMyObject){myObjects
检查以下设计的程序:#include#includetemplateusingUniPtr=std::unique_ptr>;int*alloc(){returnnewint;}UniPtrfunc(){autodealloc=[](int*p){deletep;};returnUniPtr{alloc(),dealloc};}intmain(){autop=func();return0;}来自std::functionconstructormanual,我认为构建std::function对象可能会抛出异常,即使这个比例很低:UniPtrfunc(){autodealloc=[](i