# There is no need for reference counts nor smart pointers

This topic is 4813 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi guys I have a C++ philosophical question. smart pointers and reference counting can be used for garbage collection and memory management. in case of reference counts, each time the object is referenced, u increase the counter by one, once u release it, u decrement by one until it becomes 0, at that time it is deleted. I understand that, my question is : theoretically speaking, can not we do that manually ? since the execution is done sequentially, if u are in object x having access to object y, just use y and do not care about it once u finish, leave its destruction to the guy created it. so why is all of this discussion about reference counting. I think that reference counting is really useful, but I could not figure out exactly in which cases, that is why I am trying to challenge and write the question in reverse order.

##### Share on other sites
You have a texture class, CTexture. Textures are created by a texture manager. When you come to render something, you set the current texture to something, then render.

So, the application asks the texture manager to create a texture (refcount = 1).
The application then tells the renderer to set that texture as the current texture (refcount = 2).
The application then renders something and frees the texture (refcount = 1).
In the last step, if the texture isn't refcounted, then it gets deleted, and the next time the renderer goes to access it, the program crashes. You could just "give" the object to the renderer, and then the renderer can delete it when its done, but what if you want to modify the texture and then set it as the current texture again? The renderer deletes it, and the application gets a null pointer.

Smart pointers are slightly different, since they can usually be replaced with normal pointers, but it makes like a lot easier.
Sure you can write code without the help of reference counting and smart pointers, and it might even be slightly faster (as in less than 1% faster unless theres something very messed up about your code). But your code will be absolute hell to maintain...

##### Share on other sites
There a various kinds of smart pointers,

first of all smart pointers with-out any kind of reference count are usaully written to implement RAII techniques because what would have happen in this situation:

struct foo {};void f() {   foo* bar = new foo;   g(); // what happens if g throws an exception?   delete bar;}

you'll never know if bar will ever get deleted if the function g throws an exception thus causing memory leaks.

But if we do this:

template < typename Tp >class ptr {   Tp* p;public:   ptr(Tp* _p = 0): p(_p) {}   /* omitting code */   ~ptr() { delete p }}; struct foo {};void f() {   ptr<foo> bar(new foo);   g();}

now no matter what happens if g throws an exception or not bar will always be deleted properly.

Now in the case of reference counting this usually means you wont to share an instance but the problem is if you don't do anything like a reference count who owns the instance? who is responsible to delete the instance when no body is using it any more? it also helps prevent dangling pointer syndrome.

There are other reasons for smart pointers such as using pointers in STL containers, but google will help fill in the details

##### Share on other sites
Garbage collection is merely to simplify memory management, nothing more. You could of course do everything manually (like most C programs seem to do), but that makes errors easy.

To go with your thread title ("There is no need for reference counts nor smart pointers"): There is no need for any language higher level than machine code. Good luck with manually inputting the binary (it is possible, but painful to say the least).

##### Share on other sites
If you can guarantee that an object is only going to be used by one other object, then you don't need reference counting. But this is often not the case... For example, you have a texture that contains all of your GUI Controls images (an atlas). Now you COULD create a seperate texture per GUI Control that just loads the same image, but this is a bad idea (uses up more resources, and adds to the number of state changes required to render). So, you come up with a way so that all the controls use the same texture. What do you do when you delete a control? If you delete the texture along with it, all the other controls pointing at it will stop working (or more likely, throw a nice big exception and kill your program). If you don't release/delete the texture you'll end up leaking the memory and have a texture loaded with nothing referencing it.

With simple reference counting you can Acquire the texture object when you start using it (which increments the reference count), and Release the object when your done... internally the Release will check if the reference count is down to 0 and delete itself if it is. Hooray, a very simple interface that, assuming it's used correctly, eliminates the possibility of any refcounted objects being allocated but not referenced.

"Doing it manually" in this case would require you have knowledge of everywhere in the program that a particular refcounted resource is used... while it's possible to know that in static environments it becomes impossible when you add things that you might not even have control over (such as mods or scripts) and even if it's a static environment, it's much more prone to error. Reference counting is practically free, incredibly simple, and pretty effective ... I don't know why you wouldn't want to use it (or similar techniques) for any moderate to large scale projects.

##### Share on other sites
Every programming construct has it's usefulness. If you cannot fathom a use for it then you are too narrow-minded.
Keep programming until you come across a situation where you realise that you need it. Until then, if you have no need for it (as do I at the moment) then simply do not use it.

Most constructs are either over-used, or under-used. It's possibly true that reference counting is over-used, I'll give you that.

##### Share on other sites
guys, thanks so much for input, the majority misunderstood me
I did not want to promote not using reference counting,
I asked the question in reverse order because it is the best way
to address the issue, what I needed is to get good examples where such technique is the best solution. u game me some, thanks again.

##### Share on other sites
Quote:
 Original post by silvia_steven_2000guys, thanks so much for input, the majority misunderstood meI did not want to promote not using reference counting,I asked the question in reverse order because it is the best wayto address the issue, what I needed is to get good examples where such technique is the best solution. u game me some, thanks again.

The "misunderstanding" could be due to your giving the thread the title "There is no need for reference counts nor smart pointers," which is not a question, but stating an opinion (which people are going to disagree with). Always be careful what you name your topics.

##### Share on other sites

this is what actuallay I meant to write. I did that by intention.
when u chose a strange title u get your massage read by the max
number of people.

##### Share on other sites
Quote:
 Original post by silvia_steven_2000this is what actuallay I meant to write. I did that by intention.when u chose a strange title u get your massage read by the maxnumber of people.
Ah yes, but many people will just assume you are a troll, and we all know not to feed the trolls.

##### Share on other sites
Quote:
Original post by iMalc
Quote:
 Original post by silvia_steven_2000this is what actuallay I meant to write. I did that by intention.when u chose a strange title u get your massage read by the maxnumber of people.
Ah yes, but many people will just assume you are a troll, and we all know not to feed the trolls.

Not all of us do. Take me, for example. I am an idiot(tm). I feed trolls.

Then again, sometimes the troll dies in the feeding, if my cooking is a bit off. So I suppose it's for the common good.

</random>

void simple_example_of_when_smart_pointers_would_be_nice ( void ){    int * this_should_have_been_a_smart_pointer = new int[100];    if(pie && foo)    {        if (lord_fnordicus_has_returned() && !mariners_win())        {            switch (ham_type)            {                case HAM_WITH_WHIPCREAM:                    std::cout << "EWWWW" << std::endl;                    return; //memory leak                default:                    cookie_monster += 12;                    break;            }            if (swiss_cheeze)            {                std::cout << "IT'S CHEESE YOU BUFFOON" << std::endl;                swiss_cheese = 1;                throw new pie(); //memory leak            }            else            {                if (elvis.alive()) return; //edit: I frogot to mark this as amemory leak on the first pass.            }        } else if (lord_poppeye_has_returned()) {            eat_hot_integer_array( this_should_have_been_a_smart_pointer );        }        swiss_cheese && (teh_yummeh = 1);        lolzorz || (we_are_safe = 1);    } else if (pie) {        throw std::execption(); //memory leak    } else if (foo) {        call_some_function_that_will_throw_without_us_realizing_it(); //memory leak    } else {        sexy_momma = 0;        return; //memory leak    }    delete[] this_should_have_been_a_smart_pointer; //cleanup}

##### Share on other sites
in fact, after developing program you theoretically can remove most refcounts. (in simpler programs you typically can remove all refcounts.)

How compiler can (theoretically can) remove refcounts: like any other known-at-compile-time thing.

Inline your
if(!refcount){allocate what you want;};
refcount++
and
refcount--;
if(!refcount){deallocate what you want;}

And then step along program flow and for every refcount++ and refcount-- operator check if refcount can be calculated at compile time, not at runtime .
It's quite hard but possible. And most of refcounts can be calculated at compile time.

BUT:
With complexs programs, some refcounts can't be calculated at compile time. Even in complex program it's probably small precent of 'em.

##### Share on other sites
Quote:
 Original post by silvia_steven_2000since the execution is done sequentially
I don't think anyone else has mentioned it yet, so I will. Execution does not have to be sequential. In a single-threaded program, you are correct, but reference counting can help out tremendously in multi-threaded programs. At least, that's my experience.

##### Share on other sites
A simple situation in which resource counting is useful in single-threaded situations is one where you need to keep memory use down (aka, to meet a certain "target" RAM use max, or a limit not breakable via virtual paging (embedded systems for example)).

Although you could simply load/decompress the resource for the program's lifetime, it does take up memory. Resource counting would let the application know when it could free that resource.

##### Share on other sites

This topic is 4813 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628696
• Total Posts
2984265

• 18
• 9
• 13
• 13
• 11