我正在使用auto_ptr它使用类指针类型的数组,那么我该如何为其赋值。例如auto_ptrarr[10];如何为arr赋值数组? 最佳答案 您不能将auto_ptr与数组一起使用,因为它调用deletep,而不是delete[]p。你想要boost::scoped_array或其他一些boost::smart_array:) 关于c++-将auto_ptr与数组一起使用,我们在StackOverflow上找到一个类似的问题: https://stackove
我似乎在这里遗漏了一些东西。我从boost::shared_ptr移动到std::shared_ptr。shared_ptr早在2000年代中期就已成为TR1的一部分,它应该在2012年随处可用。尝试在Apple下使用shared_ptr会得到大量undefinedreference:SecureArray.h:26:12:error:nomembernamed'shared_ptr'innamespace'std'usingstd::shared_ptr;~~~~~^SecureArray.h:27:12:error:nomembernamed'tr1'innamespace'std
首先,我知道unique_ptr和前向声明的一般问题,如Forwarddeclarationwithunique_ptr?.考虑这三个文件:啊.h#include#includeclassB;classA{public:~A();private:std::unique_ptrm_tilesets;};C.cpp#include"A.h"classB{};A::~A(){}main.cpp#include#include"A.h"intmain(){std::unique_ptrm_result(newA());}发出g++-std=c++11main.cppC.cpp会产生以下错误:I
有没有办法区分已分配(可能已过期)的weak_ptr和未分配的。weak_ptrw1;weak_ptrw2=...;我了解以下针对未转让或到期的检查,但是否有(更便宜的?)仅针对未转让的检查?if(!w.lock()){/*eithernotassignedorexpired*/} 最佳答案 您可以使用两次调用owner_before来检查默认构造的(空)弱指针是否相等:templateboolis_uninitialized(std::weak_ptrconst&weak){usingwt=std::weak_ptr;return
我知道auto意味着类型扣除。我从未见过它用作auto&,而且我不明白:在这个短代码中做了什么。#include#include#includevoidPrintMe(){std::coutthreads;for(unsignedinti=0;i我猜这是某种合成糖的替代for(std::vector::iteratorit=threads.begin();it!=threads.end();it++){(*it).join();}但我不明白这个语法是如何工作的,以及&符号在那里做什么。 最佳答案 您的示例代码几乎是正确的。在C++1
我的问题涉及shared_ptr的赋值运算符模板在GCC4.7.2中的实现,我怀疑它包含一个错误。前提1:C++11标准这里是我说的赋值运算符模板的签名:templateshared_ptr&operator=(constshared_ptr&r)noexcept;来自C++11标准(20.7.2.2.3):“等价于shared_ptr(r).swap(*this)。”换句话说,赋值运算符模板是根据构造函数模板定义的。构造函数模板的签名如下:templateshared_ptr(constshared_ptr&r)noexcept;来自C++11标准(20.7.2.2.1):“要求:除
我习惯于在返回std::unique_ptr时不使用std::move,因为这样做会禁止RVO。我有这种情况,我有一个本地std::unique_ptr,但返回类型是std::shared_ptr。以下是代码示例:shared_ptrgetInt1(){autoi=make_unique();*i=1;returni;}shared_ptrgetInt2(){returnmake_unique(2);}unique_ptrgetInt3(){autoptr=make_unique(2);returnptr;}intmain(){coutGCC接受这两种情况,但Clang拒绝getInt
由于模板参数的类型很明显,因此读/写示例的第二行会更容易:#includestructFoo{};intmain(){//redundant:goodautofoo1=std::unique_ptr(newFoo());//withoutexplicitness:doesnotcompileautofoo2=std::unique_ptr(newFoo());}当然,如果你想使用多态,我们总是可以这样写:autobase=std::unique_ptr(newDerived());这种约束的原因是什么? 最佳答案 这不是std::u
#include#include#includeusingnamespacestd;structNode{Node(intdata,boost::shared_ptrnext=boost::make_shared()):m_data(data),m_next(next){}intm_data;boost::shared_ptrm_next;};错误:http://www.compileonline.com/compile_cpp11_online.php-在线编译和执行C++11(GNUGCCversion4.7.2)Compilingthesourcecode....$g++-std
例如,我想要一个auto类型的变量,因为我不确定它是什么类型。当我尝试在类/结构声明中声明它时,它给了我这个错误:Cannotdeduceautotype.Initializerrequired有办法解决吗?structTimer{autostart;}; 最佳答案 可以,但必须声明static和const:structTimer{staticconstautostart=0;};AworkingexampleinColiru.由于此限制,您因此不能将start作为非静态成员,并且不能在不同对象中具有不同的值。如果你想要不同类型的s