简体   繁体   中英

Raw Pointer in C++

I have a piece of C++ classes and I have the raw pointer to the objects. The pointer to the object would get passed down to the function. The problem is the underlying function might need to store the pointer at times in an STL container in which pointer to the object would be used later on. If I am not using shared_ptr, I am thinking of adding a bool flag to the class which indicates whether the caller of the function is responsible for deleting the object memory. Would that be fine?

Thanks.

Messy. And rife with many potential bugs that will keep you at work well past midnight on a Saturday.

Be clear and consistent about resource ownership. Either the vector owns the pointers, or some specific function owns the pointers, or smart pointers own pointers. Any mixing of these semantics will have the ultimate result of you tearing your hair out late at night.

The best solution is usually to use a reference-counted smart pointer. (As you probably already know all to well, you can't use std::auto_ptr ) Barring that, create a class whose sole purpose in life is to allocate, deallocate and grant access to the vector's contained pointers. Any function that needs the contained object would go through your manager class to get to them.

STL containers will almost certainly take a copy of the object which you insert into it. When the object is removed from the container, the object will be destroyed.

If the default copy constructor is not sufficient (ie you need to do a deep copy of the object), you need to ensure you implement your own version which does the copy properly.

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