I’m writing a socket listener in C. Whenever it accepts, it creates a new thread (detached) recv the data and process.
But everytime, I need to manually call close(socket_descriptor). Had it been C++, I could have in someway choose to close it inside a destructor.
I was trying to find out something that provides me same behaviour.
Basically, I want to create something like shared_ptr in C.
Is there anyway in C where one can get a signal or a notification when an object is going out of scope?
No, that’s not an inherent feature of C … to enable something like what you’re asking for you would have to create some sort of call-back mechanism that would use a look-up table to match an object to its “destrutor”, and call that general call-back function at the end of every function you write, or more likely, at the end of every scope where an object was declared. I’d consider that very messy and complicated, and in the end, that’s probably much more hassle than it’s worth, i.e., you could simply use a
gotoand write all your clean-up code at the end of the function (I know in-general usinggoto‘s is considered very bad style, but for jumping to clean-up code at the end of a function, they can actually make the code much cleaner than the alternative which is to keep repeating the same clean-up code every time there’s an error).For example, suppose you had a function that allocated some memory and opened a file descriptor at some early point in the function, but then if there were some errors, could not continue … you can’t simply return an error code, you have to-do some clean-up, but it would be a pain to repeat the clean-up code over and over again right in the middle of the code:
This deliberate and judicious use of the
gotohere creates a very concise area of the function where destruction and clean-up can take place, and you don’t have to worry about possibly missing clean-up functionality had you decided to sprinkle clean-up code in the actual “mechanics” of the function itself.