I'm fairly new to C++ and when wandering around the constructor and destructor behavior I found this problem:
#include <iostream>
struct Student {
std::string a;
~Student() {
std::cout << "Destructor called\n";
}
} S;
int main() {
std::cout << "Before assigning to S\n";
S = {""};
std::cout << "After assigning to S\n";
}
When I compile the code above with g++ and run it, it prints:
Before assigning to S
Destructor called
After assigning to S
Destructor called
But when I change std::string a; to const char *a;, then it prints:
Before assigning to S
After assigning to S
Destructor called
Can anyone explain why this change makes the destructor run one fewer time?