I am new to C++, and I have some questions about how the union works. This is my code :
#include <iostream>
using namespace std;
union S
{
std::string str;
int a;
~S() {}
};
int main()
{
S s {};
s.str = "hello";
std::cout << s.str << std::endl;
s.a = 3;
std::cout << s.a;
std::cout << "This is my string : " << s.str << std::endl;
}
- If I write " S s" instead of " S s{}", i have a error --> use of the deleted function S::S().
- if I delete this line "~S() {}", i have a error --> use of the deleted function S::~S().
In this website, https://en.cppreference.com/w/cpp/language/union, it is said that because I have a member (string) with a non default constructor/destructor, it will delete the default constructor and the default destructor of the union S. My question is : Why? I still don't understand why they delete the default constructor/destructor in C++.
- Also, I have heard it is important to explicitly call the destructor if i want to switch the string to an integer because it will leads to the memory leak.My question is: Do I need to call the union destructor or the string destructor? In this code,if I need to call the union destructor, the destructor does nothing, so does that means my string won't be ereased?. If I need to call the string destructor, I don't know how to write the string destructor. Thank !
When i run this code, it shows me this :
hello
3
This is my string :
As I have expected, the last sentence "This is my string :" doesn't show me the string "hello" because I have overwrite "s.a = 3". But, it seems s.str is empty. My questions is: Why does s.str is empty. Does it mean that the compiler has called automatically the destructor of my string. Thank!
I know there are alternative like boost or variant, but I still want to understand this.