Lifetime of temporaries

G

gw7rib

I was doing a bit of experimenting prior to writing an overloaded
operator, to see when a temporary was destroyed. I'm a bit unhappy at
the result. This is my code (it's supposed to be a normal overloaded +
and =, but with the actual calculation omitted and names used for
tracking. And yes, it's a bit C-like):


#include <stdio.h>
#include <string.h>

class Thing {
char name[20];
public:
Thing(char *namein); // normal constructor
Thing(const Thing& other); // copy constuctor
~Thing(void);
Thing operator+(const Thing& in);
Thing& operator=(const Thing& in);
};

Thing::Thing(char *namein) {
strcpy(name, namein);
printf("Constructing %s\n", name);
}

Thing::Thing(const Thing& other) { // copy constuctor
strcpy(name, other.name);
strcat(name, "c");
printf("Copy constructing %s\n", name);
}

Thing::~Thing(void) {
printf("Destroying %s\n", name);
}

Thing Thing::eek:perator+(const Thing& in) {
printf("Beginning add\n");
Thing result("R");
printf("About to end add\n");
return result;
}


Thing& Thing::eek:perator=(const Thing& in) {
printf("Doing assignment\n");
return *this;
}

int main(void) {
Thing a("A"), b("B"), c("C");

c = a + b;
printf("Finished\n");
}

and this is the result:

Constructing A
Constructing B
Constructing C
Beginning add
Constructing R
About to end add
Copy constructing Rc
Destroying R
Doing assignment
Finished
Destroying Rc
Destroying C
Destroying B
Destroying A

I was expecting that the temporary (Rc) would be destroyed when the
assignment was finished, and I'm surprised that it is apparently still
around after "Finished" is printed. Will it hang around until my
program terminates or is there some way to get rid of it earlier?

Thanks for any advice.
Paul.
 
G

gw7rib

I was doing a bit of experimenting prior to writing an overloaded
operator, to see when a temporary was destroyed. I'm a bit unhappy at
the result.

[His temporary survives until the end of the enclosing scope.]

The temporary is supposed to be destroyed at the end of the statement.
Your compiler is broken, at least wrt the standard.  The Sun compiler
exhibits this behavior (or at least, it used to), unless you give it a
command-line flag that I no longer recall.

Ah. Thanks. Hopefully this won't be a problem, as I was testing the
code on my old Turbo C++ compiler but any actual code is likely to be
for VC++.

Paul.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top