I’m running the following code in Dev Studio 2010:
struct Foo
{
Foo() {cout << "Foo()" << endl;}
~Foo() {cout << "~Foo()" << endl;}
void operator ()(const int &) const {}
};
int bar[] = {0};
for_each(begin(bar), end(bar), Foo());
The output is not what I expected, and is the same in both debug and release regardless of the contents of the “bar” array:
Foo()
~Foo()
~Foo()
~Foo()
I’ve looked at the outputted assembly and I can’t for the life of me understand why the compiler is generating extra calls to the destructor. Can anyone explain to me exactly what’s going on?
This is because nameless temporary objects are being created and destroyed during the course of the program.
Usually, the standard does not provide any guarantees w.r.t creation of temporary objects while using Standard Library containers and Algorithms. Implementations are allowed to create temporary objects if they desire so(for good performance or whatever).
Note that You should follow the Rule of Three in c++03 and Rule of Five in c++11 to avoid any problems due to temporary object creation.