Question about destructors and objects

I am reading Herbert Schildt's c++ book.In the book,there is an example code:

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
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class samp{
char*s;

public:

    samp() { s='\0'; }
    ~samp() { if(s) free(s);cout << " s is being released\n";}
    void show() { cout << s << "\n";}
    void set(char *str);
};

void samp::set(char*str)
{
    s=(char*) malloc (strlen(str)+1);
    if (!s) {
        cout << "Memory allocation error!";
        exit(1);
    }
     strcpy(s,str);
}


    samp input()
    {
        char s[80];
        samp str;
        cout << "Enter a string: ";
        cin >> s;
        str.set(s);
        return str;
    }


int main()
{
    samp ob;
    ob=input();
    ob.show();
    return 0;
}


He gives the resulting screen:
Enter a string: Hello
s is being released
s is being released
Hello
s is being released
Null pointer assignment


He says that,destructor function is called 3 times.First,when the input function goes out of scope and str is returned,desctuctor is called for str object.Then it is called when temporary object(which is returned by input function) is destroyedThe third calling is,when the ob object in main() function is destroyed.at the end of the program.

By temporary object he means,when the input function is returning the object str,a temporary object is created(with the same values of str) and after the function returns and it's copied to ob object,that temporary object is destroyed.

My problem is,when I run this program(and also I have tried my own examples similar to this program) it prints two "s is being released" not three,so it seems like the destructor function is called 2 times not 3 times unlike the resulting screen in the book.

Maybe this book is a bit old and c++ standard has changed or different implementations by different compilers or...?
Last edited on
By temporary object he means,when the input function is returning the object str,a temporary object is created(with the same values of str) and after the function returns and it's copied to ob object,that temporary object is destroyed.
I don't know if a compiler ever generated such a code. It wouldn't make sense.

you have two local objects hence the destructor is called two times.

By the way: on line 42: since there's no operator= an invalid pointer is copied and hence the show() function prints garbage / the behaviour is undefined

In other words: that example is nonsense
that example? ... hmm, websearch:
http://www.seebs.net/c/c_tcr.html
http://computer-programming-forum.com/47-c-language/c97328b737945d5a.htm

At least the books teach one to be critical, trust nothing and to think.
Thanks for your answers.
Topic archived. No new replies allowed.