基于these中的答案questionshere,我知道使用c++14的std::make_unique肯定比直接emplace_back(newX)更可取。也就是说,是不是更喜欢打电话my_vector.push_back(std::make_unique("constructor","args"));或my_vector.emplace_back(std::make_unique("constructor","args"));也就是说,在添加由std::make_uniquestd::unique_ptr时,我应该使用push_back还是emplace_back/?====编辑=
TL;博士:第一个循环在HaswellCPU上运行速度提高了约18%。为什么?循环来自gcc-O0(未优化)循环使用ptr++对比++ptr,但问题是为什么生成的asm表现不同,而不是关于如何编写更好的C。假设我们有这两个循环:movl$0,-48(%ebp)//Loopcountersetto0movl$_data,-12(%ebp)//Pointertothedataarraymovl%eax,-96(%ebp)movl%edx,-92(%ebp)jmpL21L22://ptr++movl-12(%ebp),%eax//Getthecurrentaddressleal4(%eax)
我想将存储在它们的未排序vector中的unique_ptrmove到另一个vector,该vector将包含指针的排序vector。确定moveunique_ptr不会自动删除第一个vector中的元素吗?我该怎么做?我想做的例子:std::vector>unsorted,sorted;//fillthe"unsorted"vectorwhile(unsorted.size()>0){constautoit=find_next_element_to_add_to_sorted(unsorted);sorted.push_back(std::move(*it));}我希望意图很明确。更
代码:#includestructData;std::unique_ptrmake_me();intmain(){std::unique_ptrm=make_me();return0;}当然失败了:Infileincludedfrom:1:Infileincludedfrom/opt/compiler-explorer/gcc-7.1.0/lib/gcc/x86_64-linux-gnu/7.1.0/../../../../include/c++/7.1.0/memory:80:/opt/compiler-explorer/gcc-7.1.0/include/c++/7.1.0/bit
假设我有两个类(class):“Foo.h”#pragmaonceclassFoo{public:Foo(){};~Foo(){};};“啊”#pragmaonce#includeclassFoo;classA{public:A(){};~A(){};std::unique_ptrfoo;};A持有Foo的unique_ptr。我不想在“A.h”中包含Foo,所以我转发了它。通过在“A.h”中向前声明类Foo,我得到一个编译时错误:errorC2027:useofundefinedtype'Foo'errorC2338:can'tdeleteanincompletetype所以我关注了
unique_ptrmyFun(){unique_ptrpa(newA());returnpa;}constA&rA=*myFun();此代码可以编译,但rA包含垃圾。有人可以向我解释为什么这段代码无效吗?注意:如果我在取消引用之前将myFun的返回值分配给命名的unique_ptr变量,它可以正常工作。 最佳答案 unique_ptr会将所有权传递给另一个unique_ptr,但在您的代码中,没有任何内容可以从返回的指针中捕获所有权。换句话说,它不能转移所有权,所以它会被销毁。正确的做法是:unique_ptrrA=myFun()
哪种转换更好,有什么区别?classBase{};classDerived:publicBase,publicstd::enable_shared_from_this{};intmain(intargc,constchar*argv[]){std::shared_ptrptr1=std::dynamic_pointer_cast(std::shared_ptr(newDerived()));//version1std::shared_ptrptr2=std::shared_ptr(newDerived());//version2return0;} 最佳答案
我已经做了足够多的谷歌搜索知道如果我有什么喜欢classSubObject{public://blahblahblah};classAggregate{public:boost::shared_ptrm_ptr;};我可以让Doxygen创建“正确”的协作图如果我有一个像这样的虚拟声明namespaceboost{templateclassshared_ptr{T*dummy;};}在我的头文件中。我的问题是:我如何让它在我的所有项目中发挥作用以及我所有的标题,而不必实际包含该行在每个文件中? 最佳答案 呵呵....我觉得自己回答自
我有win32APICommandLineToArgvW它返回一个LPWSTR*和警告我CommandLineToArgvWallocatesablockofcontiguousmemoryforpointerstotheargumentstrings,andfortheargumentstringsthemselves;thecallingapplicationmustfreethememoryusedbytheargumentlistwhenitisnolongerneeded.Tofreethememory,useasinglecalltotheLocalFreefunction
在阅读Jossutis从他的STL书中对auto_ptr的解释后,我有一个强烈的印象,即无论我尝试在什么任务中使用它,我都会100%失败,因为auto_ptr的许多陷阱之一。我的问题是:在现实生活中是否有auto_ptr真正有用并且非常适合的任务? 最佳答案 很明显,auto_ptr输给unique_ptr.现在,在“没有增强的严格C++03”世界中,我使用auto_ptr很多时候,最值得注意的是:对于返回给定类型的动态分配实例的“工厂成员函数”:我喜欢使用std::auto_ptr在返回类型中明确指出对象必须被删除在尝试将对象插入