当你有C++17中可用的类模板参数推导时,为什么你不能推导std::unique_ptr的模板参数?例如,这给了我一个错误:std::unique_ptrsmp(newD);上面写着“类模板的参数列表丢失”。模板参数(至少是指针类型)不应该是可推导的吗?Seethis:anydeclarationthatspecifiesinitializationofavariableandvariabletemplate 最佳答案 让我们看看newint和newint[10].两者都返回int*.无法判断您是否应该拥有unique_ptr或un
如图here,std::unique_ptr有两个用于空指针的constexpr构造函数:constexprunique_ptr();constexprunique_ptr(nullptr_t);我对这两个构造函数有两个问题:为什么我们需要两个?我们不能只声明一个:constexprunique_ptr(nullptr_t=nullptr);constexpr真的有用吗?我尝试在我的代码中这样做,但它没有编译(g++6.1.0,-std=c++14):constexprstd::unique_ptrp;//error:thetype'conststd::unique_ptr'ofcon
当我尝试std::move或std::make_unique时,尝试在union中使用unique_ptr会给我一个段错误。#include#includeunionmyUnion{struct{std::unique_ptrupFloat;}structUpFloat;struct{std::unique_ptrupInt;}structUpInt;myUnion(){}~myUnion(){}};structmyStruct{intx;myUnionnum;};intmain(){myStructaStruct,bStruct;aStruct.x=1;bStruct.x=2;aut
我不知道为什么要上课std::future和std::promise没有用final说明符标记。destructor是not虚拟的,为什么没有添加final?理由是什么? 最佳答案 用std::vector看看这个人为的(当然是荒谬的)示例:templatestructExample:privatestd::vector{voiddoStuff(constT&t){this->push_back(t);}TretrieveStuff(){returnthis->operator[](0);}};Examplee;e.doStuff(
我将Doxygen用于C++项目。在构建html文档时,出现以下错误:C:/Amir/Programming/EclipseC++/CacheOptimization/src/CacheLruNaiveAlgorithm.cpp:19:warning:nouniquelymatchingclassmemberfoundforvoidCacheOpt::CacheLruNaiveAlgorithm::init(TierList&tierList,TierMap*tierMap)此警告的来源可能是什么?一般是什么原因造成的?编辑:我的DoxyfileDOXYFILE_ENCODING=UT
基于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/?====编辑=
我想将存储在它们的未排序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()