我似乎在这里遗漏了一些东西。我从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
让我们有一个名为Y的重载函数:voidY(int&lvalue){cout现在,让我们定义一个类似于std::forward的模板函数templatevoidf(T&&x){Y(static_cast(x));//Usingstatic_cast(x)likeinstd::forward}现在看看main()intmain(){inti=10;f(i);//lvalue>>T=int&f(10);//rvalue>>T=int&&}正如预期的那样,输出是lvalue!rvalue!现在回到模板函数f()并替换static_cast(x)与static_cast(x).让我们看看输出:l
如何将指向void对象的指针转换为类对象? 最佳答案 使用static_cast。请注意,只有当指针确实指向指定类型的对象时,您才必须这样做;也就是说,指向void的指针的值取自指向此类对象的指针。thing*p=whatever();//pointertoobjectvoid*pv=p;//pointertovoidthing*p2=static_cast(pv);//pointertothesameobject如果您发现自己需要这样做,您可能需要重新考虑您的设计。你放弃了类型安全,让编写无效代码变得容易:something_el
我的问题涉及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
如果你有一个不透明的指针typedef,有没有办法动态引用指向的类型,比如说,在模板中使用?例如,假设你有这样的事情:structFoo;//ForwarddeclaredstructtypedefFoo*FooPtr;//Opaquepointer因为智能指针类型在指针类型方面是模板,所以定义一个std::shared_ptr这其中,似乎不得不说:std::shared_ptrtheSharedPtr;有没有办法在不“手动”解开不透明指针typedef的情况下定义这样的指针?我觉得我必须在这里遗漏一些明显的东西,但你可能会想到这样的事情(注意:这些不起作用):std::shared_