简体   繁体   中英

automatic C++ memory/object instance management? smart pointers?

I would like to have automatic memory disposal in my C++ project.

I don't mind to have some additional conventions in order to obtain this automatic memory disposal - to be specific, I don't mind to have some special coding on creating new object instances (but of course, not anything more as it defeats the purpose).

After some readings on many useful discussions in stackoverflow, I found out that "smart pointers" are referred to the most (along with some reference of third-party c++ garbage collectors).

With only some "textbook" C++ knowledge equipped, I believe that the C++ GCs' complexities make them doesn't worth to be used, in my case.

On the other hand, I have a .NET/Java background, and would like to leverage this experience on C++ too. I'm accustomed to creating object instances and pass them to other classes/functions (I believe it is some bread-and-butter stuff in C++ too).

So, is smart pointers/shared_ptr/boost what I am looking for?

(note that for memory acquiring I mean doing a MyClass* var = new MyClass() , not malloc() .)

Some specific background:

Actually what I exactly am trying to do is to write some library functions which can be used in both C++ projects and iPhone projects (note that these are some purely logical business classes, so there should be no portability issues). Although I believe it is not an area that requires high performance (non-game app of iPhone), I have some concerns on resource usage.

Is there any issue in making use of smart pointers in this situation? Are there any better alternatives?

Consider reference counting? Create a base class that keeps a count of how often it is referenced, and deletes itself when that reference count falls to zero.

class RefCounter
{
    public:
        RefCounter() : mRefCount(1) { }
        virtual ~RefCounter() { }

        void retain() { mRefCounter++; }
        void release() {
            if(mRefCount) mRefCount--;
            if(!mRefCount) delete this;
        }

    protected:
        unsigned int mRefCounter;
};

Any referring object that needs the instance would call it's retain() function, and when done, it would call release(). The last object to call release would cause the instance to delete itself. You have to be careful to balance the retains and releases, but this technique is essentially how GC works except that GC implementations hide this reference counting from you.

I learned C++ before automatic GC became all the rage and I've never really warmed to the concept, feeling much more secure knowing exactly when and where each byte of memory was allocated and freed. But that's just me.

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