The obj1
is created on the stack. As soon as a variable on the stack gets out of scope, it is destroyed. obj1
gets out of scope when foo()
comes to its end. Therefore obj1
gets destroyed, and its destructor is called.
Furthermore, you cannot store references in an STL container like a queue
. You could use pointers or std::reference_wrapper
instead.
Have a look at this example:
#include <functional>
#include <iostream>
#include <queue>
using namespace std;
// ---------------------------------------------------------- //
struct ClassA {
ClassA(string name)
: name_(name) {
cout << "create " << name << endl;
}
~ClassA() { cout << "destroy " << name_ << endl; }
int x = 42;
string name_ = "";
};
// ---------------------------------------------------------- //
void
foo1() {
cout << "start foo1()" << endl;
ClassA obj("foo1_object");
queue<ClassA*> foo1_queue;
foo1_queue.push(&obj);
cout << "end foo1()" << endl;
}
// ---------------------------------------------------------- //
void
foo2(queue<ClassA*>& queue) {
cout << "start foo2()" << endl;
ClassA obj("foo2_object");
queue.push(&obj);
cout << "end foo2()" << endl;
}
// ---------------------------------------------------------- //
void
foo3(queue<reference_wrapper<ClassA>>& queue) {
cout << "start foo3()" << endl;
ClassA obj("foo3_object");
queue.push(obj);
cout << "end foo3()" << endl;
}
// ---------------------------------------------------------- //
int
main(int argc, char const* argv[]) {
cout << "main before foo1()" << endl;
foo1();
cout << "main after foo1()" << endl;
cout << endl;
// ---
cout << "main before foo2()" << endl;
queue<ClassA*> main_queue1;
foo2(main_queue1);
cout << "main after foo2()" << endl;
cout << endl;
// ---
cout << "main before foo3()" << endl;
queue<reference_wrapper<ClassA>> main_queue2;
foo3(main_queue2);
cout << "main after foo3()" << endl;
cout << endl;
}
This gives the following output:
main before foo1()
start foo1()
create foo1_object
end foo1()
destroy foo1_object
main after foo1()
main before foo2()
start foo2()
create foo2_object
end foo2()
destroy foo2_object
main after foo2()
main before foo3()
start foo3()
create foo3_object
end foo3()
destroy foo3_object
main after foo3()