2

I've been playing around and got curious with this following code.

struct Bar {
    Bar()=delete;
    ~Bar() { std::cout << "dtor" << std::endl; }
};

struct Foo {
    Foo(){}
    ~Foo() { std::cout << "dtor" << std::endl; }
};

Bar b(); // (A) doesn't call dtor 
Foo f(); // (B) doesn't call dtor

Foo f;   // (C) calls dtor
Bar b;   // (D) error: use of deleted function 'Bar::Bar()'

QUESTIONS

  1. Why the destructor is not called for both (A) and (B)?
  2. Is there some magic with ()?
Joseph D.
  • 11,804
  • 3
  • 34
  • 67
  • 6
    Your top two declarations don't call a constructor either, because they're not constructing an object: they're declaring a function – Tas Apr 11 '18 at 06:20
  • I'm certain there are 100 duplicates but I can't find anything at the moment, gimme a sec – Tas Apr 11 '18 at 06:21
  • 1
    Yes, `()` is magic. in the sense that It means different things in different contexts. The de-magicisation rule is that if the compiler can interpret the expression as a function prototype, it shall. – Jive Dadson Apr 11 '18 at 06:23
  • Maybe a better dupe: https://stackoverflow.com/questions/20529434/member-must-have-class-struct-union – Tas Apr 11 '18 at 06:24
  • 1
    I'm amazed there isn't an easy to find canonical – StoryTeller - Unslander Monica Apr 11 '18 at 06:24
  • Yeah I know, I had to write the faulty code to find the error it gives and look up most vexing pass, which who would know to look it up... – Tas Apr 11 '18 at 06:24
  • new term for today "most vexing parse". thanks everyone! – Joseph D. Apr 11 '18 at 06:28

0 Answers0