Home Help Center

Deleting smart pointers?

EwgenijkkgEwgenijkkg Member Ewgenij SokolovskiOrganization: RWTHProject: Rove ✭✭
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;
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;?



  • marcmarc FloridaAdministrators, ZeroC Staff Marc LaukienOrganization: ZeroC, Inc.Project: The Internet Communications Engine ZeroC Staff
    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.
  • EwgenijkkgEwgenijkkg Member Ewgenij SokolovskiOrganization: RWTHProject: Rove ✭✭

    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?
  • matthewmatthew NL, CanadaMember Matthew NewhookOrganization: ZeroC, Inc.Project: Internet Communications Engine ✭✭✭
    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.
Sign In or Register to comment.