Website Summary Files Commits Branches @commit @diff @stats
path: root / Smart_pointers
diff options
context:
space:
mode:
Commit0807aa304e771bf98274a305a258a9a9ba9d5cf7 (patch)
Author
 Angel Dimitriev <achi_d@abv.bg>
2020-03-15 21:55:20 +0200
Committer
 GitHub <noreply@github.com>
2020-03-15 21:55:20 +0200
Files24f7ffa77ba5a834869659b4edc6c973533bc6e7 /Smart_pointers
Object-oriented_programming_FMI-0807aa304e771bf98274a305a258a9a9ba9d5cf7.tar
Object-oriented_programming_FMI-0807aa304e771bf98274a305a258a9a9ba9d5cf7.tar.gz
Object-oriented_programming_FMI-0807aa304e771bf98274a305a258a9a9ba9d5cf7.zip
Parent2d09c8b018054743dcd098be08afb03e5d1ddd8d (diff)
Create 2. shared_ptr.cpp
1 files changed, 60 insertions, 0 deletions
-rw-r--r--Smart_pointers/2. shared_ptr.cpp60
diff --git a/Smart_pointers/2. shared_ptr.cpp b/Smart_pointers/2. shared_ptr.cpp
new file mode 100644
index 0000000..fc86905
--- /dev/null
+++ b/Smart_pointers/2. shared_ptr.cpp
@@ -0,0 +1,60 @@
+/******************************************************************************
+
+ Online C++ Compiler.
+ Code, Compile, Run and Debug C++ program online.
+Write your code in this editor and press "Run" button to compile and execute it.
+
+*******************************************************************************/
+
+#include <iostream>
+#include <memory>
+
+using namespace std;
+
+class Test
+{
+public:
+ Test()
+ {
+ cout<<"Test()"<<endl;
+ }
+ Test(const Test& other)
+ {
+ cout<<"Copy constructor"<<endl;
+ }
+ Test& operator=(const Test& other)
+ {
+ cout<< "Assignment operator" <<endl;
+ }
+ ~Test()
+ {
+ cout<<"Detructor"<<endl;
+ }
+
+};
+int main()
+{
+
+
+ shared_ptr<Test> smart_pointer_1(new Test());
+
+ cout<< smart_pointer_1.get() <<endl; //адресът на обекта.
+
+ shared_ptr<Test> smart_pointer_2(smart_pointer_1);
+
+ cout<< smart_pointer_1.get() << endl; //За разлика от uniqe_ptr тук smart_pointer_1 ПРОДЪЛЖАВА да сочи към обекта.
+
+ cout << smart_pointer_2.use_count() << endl; //може да видим колко пойнтера са насочени към обекта.
+ // Обектът ще се изтрие, когато пойнтерите станат 0.
+
+
+ {
+ shared_ptr<Test> smart_pointer_3 = smart_pointer_2;
+
+ cout << smart_pointer_1.use_count() << endl; //3 пойнтера към обекта ни.
+
+ }
+ cout << smart_pointer_1.use_count() << endl; // 2, защото smart_pointer_3 вече го няма.
+
+ return 0;
+} //тук изчезват пойнтерите -> броят им става 0 и обекта се изтрива(изтрива се от последния пойнтер преди да изчезне)