【C++标准模板库笔记2】智能指针shared_ptr的简单使用
2017-08-19 13:00
573 查看
/********************************************************************************************************** 文件说明: 【1】智能指针shared_ptr 【2】记住:智能指针就是指针,例如:std::shared_ptr<int> obj===========int* obj,只不过,智能指针用new 开辟的空间不需要用delete释放,智能指针会自动的释放内存空间,这防止了内存的泄露。 详细说明: 【1】shared_ptr:shared_ptr是一种智能指针(smart pointer),作用如同指针,但会记录由多少个shared_ptr共 同指向同一个对象,这便是C++中所谓的引用计数(reference counting)。一旦最后一个这样的 指针被销毁,也就是一旦某个对象的引用计数变为0,这个对象就会被自动删除。这在非环形数 据结构中防止资源泄露很有帮助。 【2】auto_ptr由于它的破坏性复制语义,无法满足标准容器对于元素的要求,因而不能放在标准容器中;如果我 们希望当容器析构时能够自动把它容纳的指针元素所指的对象删除时,通常采用一些间接的方式实现, 但是显得较为繁琐。boost库中提供了一种新型的智能指针shared_ptr,它解决了在多个指针间共享对 象所有权的问题,同时也满足容器对元素的要求,因而可以安全的放入容器中。 【3】shared_ptr最初实现于Boost库中,后来被C++标准委员会收录于TRQ技术报告中,称为C++11标准的一部分。 ***********************************************************************************************************/ #include<memory> #include<cassert> #include<iostream> using namespace std; class TestA { public: TestA(std::shared_ptr<int> dataMem):dataMem_(dataMem) { //=============================================== } void value(int i) { *dataMem_ = i; } public: std::shared_ptr<int> dataMem_; //【1】定义了一个指向整形的智能指针 }; class TestB { public: TestB(std::shared_ptr<int> dataMem):dataMem_(dataMem) { //=============================================== } int value() { return *dataMem_; } private: std::shared_ptr<int> dataMem_; }; int main() { std::cout<<"[TEST]The environment is successfully!"<<std::endl; std::shared_ptr<int> pTemp(new int(14)); TestA objA(pTemp); objA.value(12); std::cout<<*objA.dataMem_<<std::endl; std::system("pause"); return 0; }
相关文章推荐
- c++ shared_ptr智能指针使用注意事项
- C++智能指针:TR1的 shared_ptr 和 weak_ptr 使用介绍
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- C++智能指针shared_ptr的三种使用方式
- c++智能指针(三)之shared_ptr和new结合使用
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- c++ shared_ptr智能指针使用注意事项
- c++ shared_ptr智能指针使用注意事项
- utilities(C++)——单例(Singleton) (使用智能指针 shared_ptr)
- 智能指针auto_prt的使用(c++学习笔记)
- C++学习之智能指针--auto_ptr、scoped_ptr、scoped_array、shared_ptr、shared_array、weak_ptr
- 智能指针auto_prt的使用(c++学习笔记)
- 智能指针 shared_ptr 的使用方法
- C++中智能指针的简单使用
- boost库的智能指针shared_ptr结合容器vector的使用
- shared_ptr智能指针的简单实现
- c++智能指针使用笔记
- C++ 智能指针 shared_ptr
- C++boost 智能指针 share_ptr的使用