Could somebody recommend any reference/webpages to read? Thank you!
BTW, what's the relationship between reference counting and auto pointer?
Could somebody recommend any reference/webpages to read? Thank you!
BTW, what's the relationship between reference counting and auto pointer?
Any suggestions? Thanks!
i didn't quite get your question. Do you wanna have a variable that counts, for example, how many times the function have been called??
yo could do it using static variable
Code:void function()
{
static counter = 0;
counter += 1;
cout << "The function has been called for the " << counter;
if(counter == 1)
cout << " time" << endl;
else if(counter > 1)
cout << " times" << endl;
}
int main()
{
function();
}
Reference counting is used quite a bit in Objective C, and I believe you could implement it with something like this:
A class like this can only be instantiated with the MakeThing function, since the constructor is private. By using the Retain and Release methods, you can increment and decrement the reference count. Once your last pointer releases the object, it will automatically delete itself.Code:class Thing
{
private:
int RefCount;
Thing() : RefCount(1) { }
public:
static Thing *MakeThing() { return new Thing; }
void Retain() { RefCount++; }
void Release() { if (--RefCount == 0) delete this; }
//Whatever else the object does.
};
This is pretty much how the NeXTStep/OpenSTEP/Cocoa Objective C frameworks do it. There may be a better C++ method, though
Start here (and google afterwards): http://www.codeproject.com/useritems/SmartPointers.asp
Note that you didn't mention for what exactly. So its possible that you may not even need reference counting. Smart pointers can be implemented through a few other techniques (of which reference counting is one) depending on what exactly you plan to do with the allocated memory.
So, for a better picture of the whole of the whole issue of smart pointers search google for "c++ smart pointers"
There is no relationship between reference counting and std::auto_ptr, if that's what you mean by the second part of your question.
Also, don't bump your threads. Especially not after just one hour.
Here's an excellent smart pointer implementation for beginners to learn from:
http://www.josuttis.com/