Skip to content

Commit 803b891

Browse files
authored
Merge pull request #4846 from shalala66/patch-1
Update destructors-cpp.md
2 parents fbf598c + 5fd0061 commit 803b891

File tree

1 file changed

+27
-23
lines changed

1 file changed

+27
-23
lines changed

docs/cpp/destructors-cpp.md

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,38 +14,42 @@ Consider the following declaration of a `String` class:
1414

1515
```cpp
1616
// 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};
2626
};
2727

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
3132

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];
3435

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+
}
3841
}
3942

4043
// 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;
4548
}
4649

47-
int main() {
48-
String str("The piper in the glen...");
50+
int main()
51+
{
52+
String str("We love C++");
4953
}
5054
```
5155

0 commit comments

Comments
 (0)