我正在设计一个创建不同类型Foo的工厂,并且我正在尝试使用智能指针。大多数似乎都运行良好,但由于编译器的限制,我缺少一些重要的功能(即nullptr)。我有这个方法:std::unique_ptrcreateFoo(conststd::string&fooType){autoit=_registeredFoo.find(fooType);//_registeredFooisamapif(it!=_registeredFoo.end())returnstd::unique_ptr(it->second());returnstd::unique_ptr(NULL);}当我测试这个方法时,它
我在std::unique_ptrreference中看到以下注释:Onlynon-constunique_ptrcantransfertheownershipofthemanagedobjecttoanotherunique_ptr.Thelifetimeofanobjectmanagedbyconststd::unique_ptrislimitedtothescopeinwhichthepointerwascreated.有谁能举例说明一下吗?我不明白为什么。 最佳答案 您根本无法从conststd::unique_ptr移动,
这个问题在这里已经有了答案:Whydoesn'tshared_ptrpermitdirectassignment(5个答案)关闭5年前。我发现语法有编译错误。std::shared_ptrp=newint(5);3141E:\temprory(deleteitifulike)\1208.cpp[Error]conversionfrom'int*'tonon-scalartype'std::shared_ptr'requested不过没关系std::shared_ptrp(newint(5));与unique_ptr相同;但不知道为什么要禁止。
当我有一个指向单个对象的唯一指针时,我可以用reset()删除它:std::unique_ptrvariable(newchar);variable.reset();但是,这不适用于std::unique_ptr包含一个数组。为什么?删除此类指针的正确方法是什么?我正在使用EmbarcaderoC++Builder10.1。相关标准是C++11。我的观察当我有一个包含数组的唯一指针时,编译失败:std::unique_ptrvariable(newchar[10]);variable.reset();错误信息是nomatchingfunctiontocallfor'reset'.这也失
用于保护std::mutex的c++11mutexRAII类型都有一个typedef:typedefMutexmutex_type;std::lock_guard::mutex_typestd::unique_lock::mutex_typestd::scoped_lock::mutex_type这个成员typedef有什么意义?起初我认为它可以用来概括创建一个对象来移动锁(在unique_lock的情况下)例如:templatevoidfunction(SomeLockin)SomeLock::mutex_typenewMutex;//Dosomething但我无法想象它的用途。需要
是否可以使用C++11原子操作安全地moveunique_ptr?目前我有这样的代码std::unique_ptrDataManager::borrowSyncToken(){std::unique_locksyncTokenLock(syncTokenMutex);returnstd::move(syncToken);}我想知道是否有更优雅的方式,比如简单地声明:std::atomic>syncToken;并避免互斥量的需要。或者我可能根本不需要关心这里的锁并且std::move已经是原子的了?经过到目前为止的研究,在我看来:std::move本身不是原子的,需要有一些同步,否则2个
我有课。它有一个unique_ptr成员。classA{std::unique_ptrm;};我希望它适用于以下语句Aa;Ab;a=std::move(b);std::swap(a,b);如何制作?根据评论,我有一个问题。这个编译器依赖吗?如果我什么都不做,它无法通过VC++2012的编译。我试过structA{A(){}A(A&&a){mb=a.mb;ma=std::move(a.ma);}A&operator=(A&&a){mb=a.mb;ma=std::move(a.ma);return*this;}unique_ptrma;intmb;};但不确定这是否是最好和最简单的方法。
这段代码:unique_ptra;if(a){cout甚至这段代码:unique_ptra;if(static_cast(a)){cout导致此警告:warningC4800:'void(__cdecl*)(std::_Bool_struct&)':forcingvaluetobool'true'or'false'(performancewarning)with[_Ty=std::unique_ptr]在VisualStudio2012中,警告级别为3。在第一条评论之后,我发现它只有在公共(public)语言运行时支持/clr被打开时才会发生。我应该如何避免它?if(a.get()!=
我正在尝试使用unique_ptr自定义删除器映射第三方API。问题是API是这样的:x*x_alloc_x(void);voidx_free_x(x**p);API要我提供一个指向它的指针的指针,以便将其设置为NULL。我一直在编写我的deleter仿函数作为对指针的引用,我使用“&”运算符将其转换为指针对指针。structXDeleter{voidoperator(x*&p){x_free_x(&p);}};这适用于GCC4.6,但标准实际上允许这样做吗?如果没有,是否有符合标准的方法将此API映射到删除器? 最佳答案 代码格式
我问了相关问题here.现在它有点微妙。代码如下:classMyClass{public:constvector>&get_const_objs()const;private:vector>m_objs;};我的意图是从get_const_objs()返回的vector是只读的,但问题是因为vector的元素不是常量,所以调用者仍然可以更改单个元素,例如constvector>&objs=pMyClass->get_const_objs();unique_ptrp=move(objs[0]);我的解决方案是向vector中插入常量:constvector>&get_const_objs