简体   繁体   中英

How to know if my object is alive in C++?

Is there a way to know that my object is alive other than declaring a static private member in class and increment it in constructor, decrement it in destructor. Thanks in advance.

You can also do it non-intrusively to your class with STL using shared_ptr/weak_ptr.

stl::shared_ptr<YourClass> p = stl::make_shared(...); // holds a strong reference to your type
stl::weak_ptr<YourClass> wp(p);  

cout << wp.use_count(); // "1"

p.reset();

cout << wp.use_count(); // "0"

Do you mean to know if you have at least one instance of a class instantiated? A static counter is pretty much the best way. It's how I would do it anyway. :)

If the code in question lives inside a non-static method, then your object is "alive" by definition -- as long as you aren't doing something unorthodox like deleting it from inside a method.

If you are doing that (which isn't recommended unless you really know what you're doing), then make sure you NULL out the pointer immediately afterwards and always make sure to compare this against NULL to check whether your object is "alive".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM