Archived

This forum has been archived. Please start a new discussion on GitHub.

Deleting smart pointers?

Hello. Is it allowed to delete an object by deleting a smart pointer referencing it? So, for example, can I write:

IceUtil::ThreadPtr t = new MyThread;
t->start();
delete t;

In the manual I have read that I can write:

t=0;, so removing one reference to the object. And if that was the only one, the object will be deleted automaticly. But can I do the same explicitly by calling: delete t;?

Greetings
Ewgenij

Comments

  • marc
    marc Florida
    No, you cannot delete a smart pointer that has not been allocated with new (just like with any other C++ type).

    However, even if you do allocate a smart pointer with new (which is rather uncommon), then this does not necessarily delete the object the smart pointer refers to. The object is only deleted if the reference count drops to zero, which happens when the last smart pointer is destroyed.
  • exit(1)

    Hello, thanks! And what about finishing a thread by calling exit(1) in the code of this thread. So that the thread kills itself. It does work as far as I have tested. But is it really sound?
  • matthew
    matthew NL, Canada
    That doesn't just kill a thread it kills the entire application. Whether or not you want to do that depends on your application and whether leaving things in a potentially inconsistent state would cause any problems. Note that if you destroy the application prior to destroying the communicator results in undefined behaviour.