我使用boost::scoped_ptr实现了一个简单的单例:templateclassSingleton:publicboost::noncopyable{public:staticT&instance(){boost::call_once(init,flag);return*t;}staticvoidinit(){t.reset(newT());}private:staticboost::scoped_ptrt;staticboost::once_flagflag;};templateboost::scoped_ptrSingleton::t(0);templateboost::o
我有一个类能够通过TCP发送消息。这里是简化的界面:classCommandScreenshot:publicCameraCommand{public:CommandScreenshot();~CommandScreenshot();voidDispatch(boost::shared_ptrio_service);private:voidresolve_handler(constboost::system::error_code&err,boost::asio::ip::tcp::resolver::iteratorendpoint_iterator);};如您所见,我有一个函数Di
我有以下(简化的)类(class):classOperator{private:std::map>op;public:templatevoidinsertOperand(std::stringconst&s,To=T()){op.insert(std::pair>(s,std::move(std::unique_ptr(newT(o))));}voidsetOperandsValue(std::stringconst&o,intv){op.find(o)->second->setValue(v);}};插入一个新的Operand没有任何问题。然而,当函数返回时,析构函数被调用,因此ma
我试图防止裸指针,防止内存泄漏等。我还想将int映射到INuiSensor*.由于我也在使用Qt,所以我尝试使用QMap>来执行此操作,但QMap的源代码使这变得不可能:templateQ_INLINE_TEMPLATEtypenameQMap::iteratorQMap::insert(constKey&akey,constT&avalue){detach();Node*n=d->root();Node*y=d->end();Node*last=0;boolleft=true;while(n){y=n;if(!qMapLessThanKey(n->key,akey)){last=n;
我尝试使用std::ptr_fun来包装我的函数,但是当我尝试使用void参数和bool返回类型来包装一个函数时,我得到了一个错误:代码:std::functioncr=std::not1(std::ptr_fun(&funct1));功能:boolfunct1(){returnfalse;}错误:error:nomatchingfunctionforcallto'ptr_fun(bool(*)())'但每当我将参数更改为int时,问题似乎就消失了。如何使用void参数包装函数? 最佳答案 std::ptr_fun仅适用于一元函数:
使用VisualStudio2013RC和C++,我尝试将std::unique_ptr传递给已使用std::bind绑定(bind)的函数。但是,我遇到了麻烦,因为当我尝试这个时VS似乎不喜欢它。这是我要编译的内容:#include#include#includevoidfunc(std::unique_ptrarg){std::cout)>bound=std::bind(&func,std::placeholders::_1);std::unique_ptrptr(newint(42));bound(std::move(ptr));return0;}这可以在GCC4.8.1中编译,
我有一个类Library,其中包含一个结构Transaction,该结构有一个类型为Patron的成员变量。classPatron{public:Patron(){}};classLibrary{public:structTransaction{Patronp;Transaction(Patronpp):p(pp){}Transaction();};};对于Transaction的默认构造函数,我有一个函数default_transaction()返回对静态对象的const引用,正如Stroustrup在“编程-原则和实践”中所推荐的使用C++”(第324页);推理:避免在构造函数代码
我试图了解有关auto_ptr类如何工作的某些细节。假设您有以下类(class)(我是在一个网站上找到的,该网站上有人解释了赋值运算符的要点)。classTFoo:publicTSuperFoo{auto_ptrfBar1;auto_ptrfBar2;public:TFoo&TFoo::operator=(constTFoo&that);//variousothermethoddefinitionsgohere...}现在是赋值运算符的实现。TFoo&TFoo::operator=(constTFoo&that){if(this!=&that){auto_ptrbar1=newTBar
我正在尝试使用智能指针在我的类中保存COM对象,同时避免使用ComPtr。是否可以为此目的使用unique_ptr?我对智能指针很陌生,到目前为止我有点困惑。请考虑以下简化代码:classTexture{private:structComDeleter{operator()(IUnknown*p){p.Release();deletep;}}ID3D11Texture*m_dumbTexture;std::unique_ptrm_smartTexture;public:ID3D11Texture*getDumbTexture()const{returnm_dumbTexture;}ID
我正在实现一个“变体”类,它必须具有尽可能小的内存占用并使用共享指针机制存储一些对象。为此,我想在所有变量类型的类中建立一个union。这包括一些shared_ptr。operator=和复制构造函数必须更改变量的数据类型,从而切换到union中的另一个成员。切换到shared_ptr后,应将其重置为null而无需删除/取消拥有指针。有办法做到这一点吗?当然,还有其他方法可以实现这一点,但在我的例子中,它们通常更复杂、更不安全或消耗更多内存。不过欢迎提出任何建议。谢谢! 最佳答案 重置为null是不够的;的实现std::shared