forked from teseoch/CPP-Fall-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100-shared_pointer.cpp
68 lines (55 loc) · 1.64 KB
/
100-shared_pointer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <memory>
class Fruit
{
public:
int bla;
Fruit(std::string the_name) : name{the_name}
{
std::cout << "Fruit constructor: " << name << std::endl;
}
~Fruit()
{
std::cout << "Fruit destructor: " << name << std::endl;
}
void foo()
{
std::cout << "nothing" << std::endl;
}
private:
std::string name;
};
std::shared_ptr<Fruit> make_thing()
{
auto Y = std::make_shared<Fruit>("Raspberry");
auto Z = std::make_shared<Fruit>("Pineapple");
return Y;
}
int main()
{
std::cout << "main (1)" << std::endl;
/* Task 1: Modify the statement below to use a smart pointer instead of raw
dynamic allocation. */
// Fruit *A = new Fruit{"Pear"};
std::shared_ptr<Fruit> A{std::make_shared<Fruit>("Pear")};
std::cout << "main (2)" << std::endl;
/* Task 2: Try out the following statement (which would cause a memory leak
using normal dynamic allocation). */
// A = nullptr;
std::cout << "main (3)" << std::endl;
/* Task 3: Comment out Task 2 and try reassigning A to point at a new Fruit
object with the name "Grapefruit" instead. */
A = std::make_shared<Fruit>("Grapefruit");
A->foo(); //same (*A).foo();
A->bla = 10;
Fruit &f = *A;
std::cout << "main (4)" << std::endl;
// Task 4a: Create another smart pointer B and set it equal to A.
std::shared_ptr<Fruit> B = A;
// B = NULL;
// A = nullptr;
// Task 4b: Call the make_thing() function above and assign its return value to A.
A = make_thing();
std::cout << "main (5)" << std::endl;
return 0;
}