Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compiler Generated Destructor #430

Closed
ochavan9 opened this issue Jan 4, 2022 · 3 comments
Closed

Compiler Generated Destructor #430

ochavan9 opened this issue Jan 4, 2022 · 3 comments

Comments

@ochavan9
Copy link

ochavan9 commented Jan 4, 2022

Hi,
Firstly, great job with this tool. It really helps to understand what magic the compiler does with our source code, especially providing insights about the modern cpp features.
I was trying out the tool for below code snippet:
class A{};
int main(){
A a;
}
The compiler output:
class A
{
public:
// inline constexpr A() noexcept = default;
};
int main()
{
A a = A();
}

Here for the class A compiler generated a default constructor. But I don't see a destructor generated. When object 'a' goes out of scope the destructor should be called. But I don't see it in the compiler output of the tool.
Please correct me if I missed anything

@andreasfertig
Copy link
Owner

Hello @ochavan9,

thank you!

Well, that is hard to understand. Clang sees that no destructor is necessary for your code example and hence doesn't bother generating one. You can see this independently from C++ Insights in Compiler Explorer godbolt.org/z/n8hWY7KbK:

Destructor simple irrelevant trivial constexpr needs_implicit

This changes once you add a data member which requires destruction, for example cppinsights.io/s/22d2c9e4:

class D {
public:
  ~D() {}
};

class A{
  D d;
};

int main(){
  A a;
}

I hope this helps.

Andreas

@ochavan9
Copy link
Author

ochavan9 commented Jan 5, 2022

Thanks for the clarification
So, is this a clang specific optimization?
I also tried allocating on heap and invoking delete operator, but even then the destructor was not generated

class A{
};

int main(){
  A* a = new A;
  delete a;
}

So, unless you have a data member or derived part that requires destruction, the compiler does some optimization for trivial cases. Is that so?

@andreasfertig
Copy link
Owner

Hello @ochavan9,

sorry for the delay. I don't know whether it is Clang specific. However, if there is nothing to destruct, which is the case in an empty class or even a class with only builtin members, a destructor is just overhead.

Andreas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants