我试图理解为什么not_a_ref不是引用。我知道我可以通过auto&将其设为引用。我在标准中研究了一段时间,但迷路了,无法弄清楚这种行为是在哪里定义的。例子:#include#include#includestd::vectorstuff;std::vector&get_stuff(){returnstuff;}intmain(){autonot_a_ref=get_stuff();if(std::is_reference::value)std::cout 最佳答案 来自C++11草案,7.1.6.4(auto说明符)第6段:Th
取消引用临时std::shared_ptr是否安全?例子:std::shared_ptrcreate_shared_string(){returnstd::shared_ptr(newstd::string("hello"));}std::cout我担心的是,一旦取消引用完成,shared_ptr就会被销毁并且引用计数器会变为零,因此返回的原始指针不再安全。 最佳答案 whatisthelifetimeofC++temporaryobject在这种情况下,返回的std::shared_ptr直到std::cout才会被销毁已完成,因
C++11标准中的[util.smartptr.shared.io]要求operator为了shared_ptr小号:templatebasic_ostream&operator&os,shared_ptrconst&p);然而,除非我遗漏了它,否则我在[unique.ptr]中看不到任何类似的东西,而且引用en.cppreference.com同意。有没有理由区别? 最佳答案 Isthereareasonforthedifference?不,没有。与make_unique一样,这是一个“疏忽”,应该在将来添加(如果有人愿意发送提案
我知道该标准有一个关于延长临时对象生命周期的异常(exception),基本上说在构造函数中绑定(bind)一个const引用不会延长生命周期,但这是否也适用于文字?例如:classC{private:constint&ref;public:C(constint&in):ref{in}{}};如果我有一个函数返回这种类型的对象Cf(){Cc(2);returnc;}如果我知道c.ref的值会在调用者中未定义吗? 最佳答案 否。构造函数完成执行后,您将无法使用该引用。当非类类型的纯右值绑定(bind)到相同类型的const引用时,总是
我有编译器不同意一个小的C++14代码片段:#includestructunmovable{unmovable(){}unmovable(unmovable&&)=delete;};intmain(){unmovableu;autoi=[&]()->decltype(auto){returnu;};auto&uu=i();assert(&uu==&u);}该程序被g++4.9.3、g++-5.1.0、g++-5.2.0和VisualStudio2015接受,但不被clang++-3.7接受。clang++-3.7推断返回类型为unmovable(值)而不是unmovable&。如果程序
#include#include#includeusingnamespacestd;structBinaryTree{intelement;shared_ptrleft;shared_ptrright;};intmain(){vector>vecBT;//caseIvecBT.emplace_back(newBinaryTree{10,nullptr,nullptr});//caseIIvecBT.emplace_back(shared_ptr(newBinaryTree{20,nullptr,nullptr}));return0;}http://en.cppreference.com
我正在尝试使用std::unique_ptr使用自定义内存分配器。基本上,我有自定义分配器,它们是IAllocator的子类,它提供了以下方法:void*Alloc(size_tsize)templateT*AllocArray(size_tcount)voidFree(void*mem)templatevoidFreeArray(T*arr,size_tcount)由于底层内存可能来自预分配block,因此我需要特殊的...Array()-分配和释放数组的方法,它们分配/释放内存并调用T()/~T()在范围内的每个元素上。现在,据我所知,std::unique_ptr的自定义删除器|
我看到一些错误传递std::vector>周围有std::move.重现问题的代码是这样的:#include//forstd::unique_ptr#include//forstd::move#include//forstd::vectorstructbar{};usingvtype=std::vector>;structfoo{foo(vtypev):_v(std::move(v)){}private:vtype_v;};vtypegetVector(){return{std::move(std::unique_ptr(newbar()))};};intmain(){foof(std
可能我不是第一个发现std::exception_ptr可用于实现any类型(性能考虑被搁置)的人,因为它是可能是C++中唯一可以容纳任何东西的类型。然而,谷歌搜索并没有在这方面带来任何结果。有人知道以下方法是否已在任何地方使用过吗?#include#includestructWrongTypeError:std::exception{};classAny{public:templatevoidset(Tt){try{throwt;}catch(...){m_contained=std::current_exception();}}templateTconst&get(){try{st
这个问题在这里已经有了答案:CanIlist-initializeavectorofmove-onlytype?(8个答案)关闭5年前。我尝试在vector声明期间移动一些unique_ptr,但出现错误。我认为我在不知情的情况下进行了复制。我不明白为什么我在声明时遇到问题,而它在push_back期间工作得很好。我用几行简化了问题。#include#include#includeusingnamespacestd;intmain(){unique_ptri1=make_unique(142);unique_ptri2=make_unique(242);unique_ptri3=mak