@@ -14,38 +14,42 @@ Consider the following declaration of a `String` class:
14
14
15
15
``` cpp
16
16
// spec1_destructors.cpp
17
- #include < string>
18
-
19
- class String {
20
- public:
21
- String( char * ch ); // Declare constructor
22
- ~ String(); // and destructor.
23
- private:
24
- char * _ text;
25
- size_t sizeOfText ;
17
+ #include < string> // strlen()
18
+
19
+ class String
20
+ {
21
+ public:
22
+ String (const char * ch); // Declare the constructor
23
+ ~ String(); // Declare the destructor
24
+ private:
25
+ char * _ text{nullptr} ;
26
26
};
27
27
28
- // Define the constructor.
29
- String::String( char * ch ) {
30
- sizeOfText = strlen( ch ) + 1;
28
+ // Define the constructor
29
+ String::String(const char* ch)
30
+ {
31
+ size_t sizeOfText = strlen(ch) + 1; // +1 to account for trailing NULL
31
32
32
- // Dynamically allocate the correct amount of memory.
33
- _ text = new char[ sizeOfText ] ;
33
+ // Dynamically allocate the correct amount of memory.
34
+ _text = new char[sizeOfText];
34
35
35
- // If the allocation succeeds, copy the initialization string.
36
- if( _ text )
37
- strcpy_s( _ text, sizeOfText, ch );
36
+ // If the allocation succeeds, copy the initialization string.
37
+ if (_text)
38
+ {
39
+ strcpy_s(_text, sizeOfText, ch);
40
+ }
38
41
}
39
42
40
43
// Define the destructor.
41
- String::~ String() {
42
- // Deallocate the memory that was previously reserved
43
- // for this string.
44
- delete[ ] _ text;
44
+ String::~ String()
45
+ {
46
+ // Deallocate the memory that was previously reserved for the string.
47
+ delete[ ] _ text;
45
48
}
46
49
47
- int main() {
48
- String str("The piper in the glen...");
50
+ int main()
51
+ {
52
+ String str("We love C++");
49
53
}
50
54
```
51
55
0 commit comments