Update 1: Added the print of "this" as suggested.
Update 2: Separate multiple files to try and stop gcc from optimizing.
Update 3: Recorded the copy constructor and introduced add functions.
Update 4: Added output from Clang and second cout basically.
I expect parameter destructors to be called as the last statements in the function. From now on, I expect the following output from the code below.
default constructor: 008DFCF8 other constructor: 008DFCEC copy constructor: 008DFBC0 in member add destroying: 008DFBC0 copy constructor: 008DFBB8 copy constructor: 008DFBB4 in function add destroying: 008DFBB4 destroying: 008DFBB8 3 == 3 end of main destroying: 008DFCEC destroying: 008DFCF8
When using MSVC (Visual Studio), the output is as expected. But GCC (4.8.2-19ubuntu1) displays the following, which shows that destructors for function parameters are called after the first cout statement in main (), but until the last.
default constructor: 0x7fff2fcea510 other constructor: 0x7fff2fcea520 copy constructor: 0x7fff2fcea550 in member add copy constructor: 0x7fff2fcea540 copy constructor: 0x7fff2fcea530 in function add 3 == 3 destroying: 0x7fff2fcea530 destroying: 0x7fff2fcea540 destroying: 0x7fff2fcea550 end of main destroying: 0x7fff2fcea520 destroying: 0x7fff2fcea510
For those who are interested in what clang ++ (3.4-1ubuntu3) produces.
default constructor: 0x7fff52cf9878 other constructor: 0x7fff52cf9870 copy constructor: 0x7fff52cf9860 copy constructor: 0x7fff52cf9858 in function add 3 == copy constructor: 0x7fff52cf9850 in member add 3 destroying: 0x7fff52cf9850 destroying: 0x7fff52cf9858 destroying: 0x7fff52cf9860 end of main destroying: 0x7fff52cf9870 destroying: 0x7fff52cf9878
Questions:
- My initial suspicion is that GCC is inserting functions? If true, is there a way to disable this optimization?
- Which section in the C ++ specification will allow destructors to be called after the main output of cout? Nesting rules are especially interesting if necessary, and when destructors are planned.
// Test.h
// Add.cpp
// Main.cpp
Compiled for GCC using:
g++ -c Add.cpp -o Add.o ; g++ -c Main.cpp -o Main.o ; g++ Add.o Main.o -o test
source share