Run time error or memory leak problem?

Pages: 12
> I understand now that I have to delete the memory allocated in (name) for this overloaded operator to work.

No. If the pointers would not be null, the right way to do it would be:
1
2
3
4
// copy over values
// delete name;
// name = new string(*rhs.name);
*name = *rhs.name ; // deep copy the string 

This avoids the situation where we deleted the old name, and the new fails
(the object would be left in an invalid state with a dangling pointer)

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
struct Circle
{
    // ...

    Circle& operator= ( const Circle& that )
    {
        assert( is_valid() && that.is_valid() ) ; // sanity check

        /******************** this is the long-winded way of doing it
        if( this != std::addressof(that) ) // if not trivial self assignment
                                           // if the object is not being assigned to itself
        {
            // we are ok if this throws; assignment fails, and the object is left unchanged
            const auto temp_ptr = new std::string(*that.name) ;

            delete name ;  // this will never fail
            name = temp_ptr ; // this will never fail
        }
        ******************************************************/

        *name = *that.name ; // short, sweet and correct
                             // if this throws, std::string would do the right thing

        assert( is_valid() ) ;
        return *this ;
    }

    // ...

    std::string* name ; // invariant: not null

    bool is_valid() const
    {
        // return true if the object is in a valid state
        return name != nullptr ;
    }
};
Topic archived. No new replies allowed.
Pages: 12