-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathitem13.cpp
More file actions
59 lines (48 loc) · 1.17 KB
/
item13.cpp
File metadata and controls
59 lines (48 loc) · 1.17 KB
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
// Item 13: Use objects to manage resources.
#include <iostream>
using namespace std;
class Dog
{
public:
Dog ( int aAge=0, string aBreed="" );
~Dog();
void ToString ( );
private:
int age;
string *breed;
};
Dog::Dog ( int aAge, string aBreed ):
age ( aAge ),
breed ( new string (aBreed))
{}
void Dog::ToString ( )
{
cout << "Age: " << age << "; Breed: " << *breed << endl;
}
Dog::~Dog()
{
delete breed;
cout << "Deleted Dog" << endl;
}
Dog* createDog( int age, string breed )
{
return new Dog ( age, breed );
}
int main()
{
std::auto_ptr<Dog> d(createDog(10, "bull dog"));
d->ToString();
// d is now null d1 points to the Dog object d previously did.
// Refer notes for more details.
std::auto_ptr<Dog> d1(d);
d1->ToString();
// This will fail
//d->ToString();
}
/*
Notes:
This odd copying behavior, plus the underlying requirement that resources managed by auto_ptrs
must never have more than one auto_ptr pointing to them, means that auto_ptrs aren't the best way to
manage all dynamically allocated resources. For example, STL containers require that their contents
exhibit "normal" copying behavior, so containers of auto_ptr aren't allowed.
*/