3

I have this C++ code:

#include <iostream>
#include <vector>

class Obj {
public:
  Obj() {
    std::cout << "build" << std::endl;
  }
  ~Obj() {
    std::cout << "destroy" << std::endl;
  }
};

static std::vector<Obj> s = { Obj() };

int main() {
  return 0;
}

And the output is

build
destroy
destroy

So why does the object get destroyed twice? Shouldn't it only get destroyed once?

cocomac
  • 518
  • 3
  • 9
  • 21
zRegle
  • 57
  • 4
  • 3
    Add the address of `this` to the `cout` call in the destructor... – Andrew Henle May 19 '23 at 03:39
  • 2
    There's probably a copy construction occuring somewhere? – Solomon Ucko May 19 '23 at 03:41
  • 1
    You may want to read about implicit contractors. – 273K May 19 '23 at 03:42
  • You may also want to try `static std::vector s(1);` instead. – Ted Lyngmo May 19 '23 at 03:44
  • 1
    Here's a demo that should clarify what's happening: https://cpp.godbolt.org/z/Ydcbfbcfr. You can try changing the code and see what happens as a result. – Solomon Ucko May 19 '23 at 03:49
  • 1
    You didn't exhaust all the ways an `Obj` can be creatged. (Hint: there is an implicit `Obj(Obj const&)` that you didn't implement but it exists anyhow). – alfC May 19 '23 at 04:43
  • 1
    If you are going to add prints to the constructor and destructor make sure you print in all the constructors. Remember there are several constructors that the compiler will generate automatically for you (so you should override those and add print). See Rule of 3/5 – Martin York May 19 '23 at 04:59

0 Answers0