#include<iostream>
#include<cstring>
#include<string>
#include<memory>
using namespace std;
class Simple
{
public:
Simple(int p = 0)
{
number = p;
std::cout << "Simple::" << number << std::endl;
}
~Simple()
{
std::cout << "~Simple::" << number << std::endl;
}
void PrintSomething()
{
std::cout << "PrintSomething:" << info_extend.c_str() << std::endl;
}
std::string info_extend;
int number;
};
void TestSharedPtr()
{
std::shared_ptr<Simple> my_memory(new Simple(1));
if(my_memory.get())
{
my_memory->PrintSomething();
my_memory.get()->info_extend = "Additon";
my_memory->PrintSomething();
(*my_memory).info_extend += "other";
my_memory->PrintSomething();
}
}
int main()
{
TestSharedPtr();
return 0;
}
编译:g++ -std=c++11 -o test.exe ptr.cpp
[jingsia@localhost ~]$ ./test.exe
Simple::1
PrintSomething:
PrintSomething:Additon
PrintSomething:Additonother
~Simple::1
本文通过一个示例程序展示了C++中智能指针(shared_ptr)的使用方法及其如何管理对象的生命周期。代码中定义了一个名为Simple的类,并通过智能指针管理该类的实例。演示了智能指针如何跟踪对象引用并自动调用析构函数。
1万+

被折叠的 条评论
为什么被折叠?



