0
InitMyObject(MyObject* ptr)
{
    *ptr = MyObject();
}

struct Data
{
    MyObject obj;
};

extern Data data;


// ...

InitMyObject(&data.obj); 

delete &data.obj; // ? is this ok

How I can delete (call deconstructor) data.obj, I also try Data::obj as pointer (nullptr default) then pass the pointer but crashed on Init.

  • 4
    Why are you trying to do this? What's the actual problem you're trying to solve? – Stephen Newell Sep 15 '21 at 13:12
  • 6
    `delete` is only used to destroy objects created with `new`. You didn't use `new` so `delete` shouldn't be used either. – François Andrieux Sep 15 '21 at 13:12
  • 1
    `obj` will be automatically destroyed whenever `data` happens to get destroyed. You haven't really shown what `data` is so we can't say if or when its destruction own would occur. – François Andrieux Sep 15 '21 at 13:13
  • 1
    You don't; it is destroyed when its containing object is destroyed. There is a list of good books [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Sep 15 '21 at 13:13
  • @StephenNewell i try clean up static data when program exit so i want call deconstruct on my obj variabl which in static struct –  Sep 15 '21 at 13:14
  • 1
    _"i want call deconstruct on my obj variabl which in static struct"_ that will happen [without your intervention](https://stackoverflow.com/questions/12728535/will-global-static-variables-be-destroyed-at-program-end). – Drew Dormann Sep 15 '21 at 13:15
  • I'm _guessing_ about the code that's missing from your question, but it is likely that your `*ptr = MyObject();` is replacing a default-constructed `MyObject` with an identical default-constructed `MyObject`. There already exists an object at that location. – Drew Dormann Sep 15 '21 at 13:20
  • @t.niese it could be! Without knowing what `MyObject` is, I'm _stressing_ the _guessing_. – Drew Dormann Sep 15 '21 at 13:29

1 Answers1

1

How I can delete (call deconstructor) data.obj

The destructor of data will destroy its subobjects. Since data has static storage, it is automatically destroyed at the end of the program.

delete &data.obj; // ? is this ok

No. You may only delete the result of a non-placement new expression. You may not delete a pointer to a member object.

eerorika
  • 232,697
  • 12
  • 197
  • 326