How to free memory in this operator overloading definition?

This is the declaration of a class called String.
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
// string1.h -- fixed and augmented string class definition
#include <iostream>
using std::ostream;
using std::istream;

#ifndef STRING1_H_
#define STRING1_H_
class String
{
    private:
        char * str;             // pointer to string
        int len;                // length of string
        static int num_strings; // number of objects
        static const int CINLIM = 80;  // cin input limit
    public:
        // constructors and other methods
        String(const char * s); // constructor
        String();               // default constructor
        String(const String &); // copy constructor
        ~String();              // destructor
        int length () const { return len; }
        void stringlow();
        void stringup();
        int has(char c) const;
        // overloaded operator methods    
        String & operator=(const String &);
        String & operator=(const char *);
        char & operator[](int i);
        const char & operator[](int i) const;
        // overloaded operator friends
        friend bool operator<(const String &st, const String &st2);
        friend bool operator>(const String &st1, const String &st2);
        friend bool operator==(const String &st, const String &st2);
        friend ostream & operator<<(ostream & os, const String & st);
        friend istream & operator>>(istream & is, String & st);
        friend const String operator+(const String& st1, const String& st2);
        // static function
        static int HowMany();
};
#endif


This is the definition of the overloaded + operator, where I must use new to allocate the memory. However, there seems no place I can use a delete to free the memory pointed by ps.

1
2
3
4
5
6
7
8
9
String operator+(const String & s1, const String & s2)
{
    int len = s1.chars + s2.chars;
    char * ps = new char [len + 1];
    std::strcpy(ps, s1.str);
    std::strcat(ps, s2.str);
    String temp(ps);
    return temp;
}


1
2
3
4
5
6
7
8
9
10
String operator+(const String & s1, const String & s2)
{
    int len = s1.chars + s2.chars;
    char * ps = new char [len + 1];
    strcpy(ps, s1.str);
    strcat(ps, s2.str);
    String temp(ps);
    delete [] ps, ps = 0;
    return temp;
}
Thanks.
Does the ps=0 statement set the ps pointer to NULL? Is it necessary to do so?
Yes, it sets ps to null. It isn't necessary to do so in this case, but if you weren't returning immediately it would be. I do it instinctively.
Topic archived. No new replies allowed.