shared_ptr<T>ptr(newT);// T可以是int、char、class等各种类型shared_ptr<std::string>sps(newstd::string("smart"));// 一个string的shared_ptrassert(sps->size() ==5);// 使用箭头操作符->shared_ptr<int>dont_do_this(newint[10]);// 错误用法,不能正确释放内存 增加计数 被引用会增加计数 ...
std::shared_ptr<int> p6(new int[10], std::default_delete<int[]>()); //自定义释放规则 void deleteInt(int*p) { delete []p; } //初始化智能指针,并自定义释放规则 std::shared_ptr<int> p7(new int[10], deleteInt); 四shared_ptr常用函数 get()函数,表示返回当前存储的指针(就是被shared...
intmain(){ std::shared_ptr<std::string>p1=std::make_shared<std::string>("hello"); autop2=std::make_shared<int>(100);// 表示指针 p2 可以指向 int 类型的对象 std::cout<<*p1<<std::endl; std::cout<<*p1<<std::endl; std::vector<int>list={1,2,3}; list.push_back(9); for(...
#include<iostream>#include<memory>#include<string>intmain(intargc,char* argv[]){// 创建一个空stringstd::shared_ptr<std::string> p1 = std::make_shared<std::string>();// std::shared_ptr<std::string> p1 = std::make_shared<std::string>(""); // 与上面语句等价// auto p1 = std:...
const std::string& logLevel = "", std::shared_ptr<HomeSpeech::ExternalMicrophoneInterface> externalMicWrapper = nullptr, std::function<std::shared_ptr<HomeSpeech::ExternalMediaPlayerInterface>(std::shared_ptr<alexaClientSDK::avsCommon::sdkInterfaces::HTTPContentFetcherInterfaceFactoryInterface> content...
#include<iostream>#include<memory>intmain(){auto*p=newstd::string("hello");std::shared_ptr<std::string>sp1(p);/*不要这样做!!*/std::shared_ptr<std::string>sp2(p);return0;} 这样会导致两个shared_ptr管理同一个对象,当其中一个被销毁时,其管理的对象会被销毁,而另外一个销毁时,对象会二次...
引用计数指的是,所有管理同一个裸指针(raw pointer)的shared_ptr,都共享一个引用计数器,每当一个...
在c++ 98 里面只有一种智能指针,就是 std::auto_ptr,因为具有唯一所有权的特征,所以限制了它的使用范围,比如你无法在容器中使用它。而我们知道 stl 容器是值语义的,如果不能用智能指针管理的话,只有两种办法来使用。 一种是类似这样: std::vector<std::string> names; ...
所以“改用shared_ptr”一般是整个项目的技术决策者来把握的事情,这里面还有要求“团队成员都要掌握正确使用shared_ptr方法”的成本。本身delete this和shared_ptr是冲突的。virtual void destroy() { delete this; } 对于字符串操作,就要求我们尽量不要用 std::string、CString 这样现成的东西,而是使用 strncpy、...
();}private:std::string name_;};intmain(){autonode=newNode("test");std::shared_ptr<Node>ptr1(node);std::cout<<"ptr1. count:"<<ptr1.use_count()<<" name:"<<ptr1->name()<<std::endl;// std::shared_ptr<Node> ptr2(node); // Error// std::shared_ptr<Node> ptr2 = ptr...