Reputation: 155
i am wondering why if i have code like this:
class Test2 {
public:
Test2() { std::cout << "TEST2 Constructor\n"; }
~Test2() { std::cout << "TEST2 Destructor\n"; }
};
class Test {
public:
static Test2& get() { static Test2 test{}; return test; }
};
int main()
{
auto test = Test::get();
std::cout << "Created\n";
auto test1 = Test::get();
std::cout << "Created\n";
auto test2 = Test::get();
std::cout << "Created\n";
}
i've got output like this:
> TEST2 Constructor
> Created
> Created
> Created
> TEST2 Destructor
> TEST2 Destructor
> TEST2 Destructor
> TEST2 Destructor
Why destructor is beeing called four times? Isn't there should be only one instance of Test?
Upvotes: 0
Views: 347
Reputation: 1881
Destructor is being called 4 times as there are 4 objects that got created. This statement
auto test1 = Test::get();
calls the copy-constructor of Test
class. You can verify by having a copy constructor with cout
statement. auto
resolves to Test
not Test&
. If you want to get the reference of the object, it has to be said explicitly
auto& test1 = Test::get();
Always follow Rule of 3/5/0 if you are definining your own implementations for destructor/copy/move constructor.
Upvotes: 1
Reputation: 63124
test
, test1
and test2
are all instances of Test
, and they get destructed at the end of main
as expected. You do not see them get constructed because you didn't instrument the move-constructor with which they are initialized.
Upvotes: 0