EffectiveModernC++(第136页)使用以下示例来激发std::weak_ptr。缓存被定义为一个无序的映射,具有指向对象的弱指针作为值。每当此缓存的客户端请求一个对象(通过键)时,就会查找相应的弱指针并在其上调用lock()。如果生成的std::shared_ptr不是null,则返回它。否则,对象从外部数据库重新加载,进入缓存并返回std::shared_ptr。现在的问题是:人们可能认为可以在没有std::weak_ptr的情况下实现这一点,而是将强共享指针存储为缓存值。如果强指针的use_count()为1,则表示客户端的所有指针都已销毁。这个例子的重点是使用st
在我广泛使用nVidiaCUDA的项目中,我有时会使用Thrust来做它做得非常非常好的事情。Reduce是一种在该库中实现得特别好的算法,reduce的一个用途是通过将每个元素除以所有元素的总和来规范化非负元素的vector元素。templatevoidnormalise(Tconst*constd_input,constunsignedintsize,T*d_output){constthrust::device_ptrX=thrust::device_pointer_cast(const_cast(d_input));Tsum=thrust::reduce(X,X+size);t
当我这样做时出现异常:std::bad_weak_ptr->shared_from_this()templateclasspainter_record_t{.......private:std::shared_ptr_owner;}这里我想在构造函数中设置“问题”对象:templateclassstream_record_t:publicpainter_record_t{public:stream_record_t(std::shared_ptrowner):painter_record_t(owner){//...}}我有基类:classi_painter_t{public:virt
我想知道是否可以使用多个参数(标准删除器签名)为std::unique_ptr指定自定义删除器。我知道std::shared_ptr存在std::bind的解决方法,这使得它成为可能但是std::unique_ptr存在一些技巧吗?对我来说似乎不是因为根据http://en.cppreference.com/w/cpp/memory/unique_ptr:Typerequirements-DeletermustbeFunctionObjectorlvaluereferencetoaFunctionObjectorlvaluereferencetofunction,callablewit
在下面的代码示例中,只要B的任何对象存在,就应该在structB中存在一个structA的实例.示例按预期工作。#include#include#includestructA{A(){std::coutguard(mtx);if(!refCount){a.reset(newA);}++refCount;}~B(){std::coutguard(mtx);--refCount;if(!refCount){a.reset();}}staticstd::unique_ptra;staticstd::mutexmtx;staticintrefCount;};std::unique_ptrB::
我正在尝试使用shared_ptr在C++中实现LazyConcurrentList-basedSet。我的推理是unreachablenodes将被最后一个shared_ptr自动释放。根据我的理解,shared_ptr的引用计数的递增和递减操作是原子的。这意味着只有引用该节点的lastshared_ptr应该为该节点调用delete/free。我为多线程运行程序,但我的程序崩溃并出现错误doublefreecalled或只是SegmentationFault(SIGSEGV)。我不明白这怎么可能。下面给出了我的实现代码,方法名称表示它们的预期操作。#include#include#
我有一个来自“C++标准库扩展”的问题:Exercise6IsaidinSection2.4.2thatyoushouldn'tconstructtwoshared_ptrobjectsfromthesamepointer.Thedangeristhatbothshared_ptrobjectsortheirprogenywilleventuallytrytodeletetheresource,andthatusuallyleadstotrouble.Infact,youcandothisifyou'recareful.It'snotparticularlyuseful,butwrit
我正在使用boost1.37,我正在尝试使用boost::ptr_vector,并转移它的所有权,以便我可以从函数中返回它。查看boost文档(http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/tutorial.html#new-functions)std::auto_ptr>get_zoo(){boost::ptr_dequeresult;...returnresult.release();//giveupownership}...boost::ptr_dequeanimals=get_zoo();我试过:#inc
我收到一个编译错误,说scoped_ptr的复制构造函数是私有(private)的,代码片段如下:classa{};structs{boost::scoped_ptrp;};BOOST_PYTHON_MODULE(module){class_("s");}虽然这个例子适用于shared_ptr。如果有人知道答案,那就太好了。谢谢 最佳答案 boost::scoped_ptr的语义禁止复制,而shared_ptr旨在被复制。您得到的错误是编译器告诉您某些代码(宏扩展?)正在尝试复制scoped_ptr但库不允许进行复制。
如果我想将dynamic_cast与shared_ptr一起使用,我可以使用dynamic_pointer_cast。如果我想转换auto_ptr,我该用什么?我假设如下所示。structB:A{};...auto_ptrbase(...);auto_ptrderive=dynamic_pointer_cast(base);我正在为shared_ptr使用boost 最佳答案 auto_ptrbase(...);if(B*query=dynamic_cast(base.get())){//takeownershipbase.rele