Archived

This topic is now archived and is closed to further replies.

MtSMox

Safe Pointers

Recommended Posts

Hi, I''m currently working on a GUI. In it I have windows (duh...). Pointers to the window are shared throughout the program. But I have one problem. Those pointers are invalid when I delete the window. So I have to make something to let the other pointers know they''re invalid. That''s why I came up with the "Safe Pointers". But how to implement them. It should be a class that lifes as long as there are pointers going on in the program to the window it points to. If something wants to delete the window it calls class.release() which makes the pointer invalid. But when to delete the class. And how to keep track of the pointers handed out? Is there a certain design pattern for this? thanks, Mox

Share this post


Link to post
Share on other sites
"shared throughout the program". eek.

I don''t know exactly what u mean by that, but it sounds bad. An object should not have to have direct pointers to the windows, rather a class that it can interface with which keeps track of pointers. Make your classes more cohesive. There''s no reason, for example, an object of class Monster to know about what windows are active. Instead, give it a pointer to a WindowManager object that does need to know what is and isn''t active. When a window closes, it only has to notify one object (The WindowManager) it has closed. Similarly, Monster only has to worry about one class. Much nicer.

Share this post


Link to post
Share on other sites
sounds like you were speaking of smart pointers. reference counted or reference linked ones, that is. only this approach has two disadvantages: the first it shares with java and any other garbage collected languages. it''s the problem of timely finalization and possible unnoticed memory leaks. when there''s a lot of pointers around, nothing will be deleted, or garbage collected. therefore, ressource leaks will most definitely occur if you keep storing the same pointer in a lot of different places. the solution is well known from java: add a dispose() method to xour class and have every access to an already disposed instance throw an exception. this way you''re gonna find those places where your window, for example, that you had thought long since gone is still referenced. of course, you will only notice when in these strange places the stored refs are also USED, so take my advice and make it your habit never to store a ptr to anything you''re not planning to use. at least, you can free any non-memory ressources in the dispose() method, so that even if a memory leak occurs in your program because of forgotten and unused ptrs, those ressources won''t be leaked, too.
the second problem of the ref counting/ref linking approach is that circularly referenced objects will never be deleted because their ref count will never reach zero. but if this problem occurs in your gui library then your code is real shit. (i hope you know that two windows should NEVER point to each other for the purpose of notification. now you''ve got one more reason to have these things managed in a seperate place)

conclusio: use ref counted or ref linked smart ptrs and seperate cleanup from destruction. that means, only if it wasn''t already disposed at destruction time (which should always be regarded an error) the destructor calls dispose() for cleanup and (important!) writes an angry line to a log file so you can easily fix it. this is exactly what i use finlizers in java for (together with an every 10 seconds call of System.GC.collect(), if practicable). of course, all finalizers are gone in release code.

the reason this ain''t a design pattern is that is is very simpla and has been long since know.

p.s. why are you writing your own gui framework?

shadi

Share this post


Link to post
Share on other sites
quote:
Original post by shadi
the solution is well known from java: add a dispose() method to xour class and have every access to an already disposed instance throw an exception.

This solution does not apply to C++, as the results of calling a member function on an invalid pointer are undefined. You cannot guarantee that dispose() will be called, or that the exception will be thrown.
quote:

the reason this ain''t a design pattern is that is is very simpla and has been long since know.

It is a design pattern. It''s called "Smart Pointer".

MtSMox: check out the smart pointers on the Boost Website.

Share this post


Link to post
Share on other sites
Ok, it''s not that generally used, but I use the class window to be able to interface with the window.
Part of my GUI is based on callbacks. The callback is called to notify the user that an event has occured whithin a window. I pass a pointer to the window in question along so it can be used.
Those pointers are also used by my input part. The mousecursor notifies the window it is hovering over of mouse-event. The pointer to that window can become invalid (even in between 2 events: eg left mouse up, right mouse down). But I think I''m going to change this part, so the pointer is automatically changed if the window order changes.
But still the window pointer used by a user could become invalid, or should this just give an exception, because it''s just too bad The user should have known it was being deleted.

But the smart pointer is kind of what I was going for. I just have to add some things to make it work the way I want to. I''ll just think this all over and try to make it work...

Mox

ps. Why am I making a GUI framework? Should I just use Windows controls in my game?

Share this post


Link to post
Share on other sites
Yes, of course. Technically, that''s absolutely no problem to use windows controls in your directx app, as long as you''re temporarily switch to flipping by the windows api''s bitblt function, so the controls dont get overridden and the main surfaces don''t get swapped all the time, that would be ugly. And for the looks... Just write an appropriate windows xp theme and have your game apply it at startup and restore the original one when closing or task switching. :-) (that was a joke)

In fact, I do use windows controls sometimes in my windows games, but only for special purposes and where it doesn''t look too bad. And bitblt()-ing the attached surface to the screen works quit well for this purpose, so the game screen doesn''t have to freeze when controls are visible.

For example, I like to use the windows default dialogs for opening/saving files, because they are so much more practical for browsing directories where appropriate and necessary than the things I would write myself. combo boxes do a nice job, either, just like grouped radio buttons and sometimes even labels.

Besides, I like to write real dialog windows, of course frameless and with a background of choice, like made (half)transparent by bitblt()-ing the attached surface. For animations keeping running in the background I have any transparent controls, including of course the full-screen main window itself, repainting (including bitblt() of course) themselves once per frame (informed via a linked list of java-like event listener objects).

But I don''t yet see a way to avoid flickering of user painted elements unless every one of them is placed on a non-transparent region that is excluded from update (sub window, for example, or explicit manual exclusion, depends on purpose). For regions that are hidden by a window this problem doesn''t exist, because the windows api''s bitblt() function uses a GC that simply won''t ever override any hidden regions.

I prefer only to use windows controls (including image controls and controls I have written myself)

Very important: don''t forget to place delays of 5 ms or the like in your app''s main loop for else everything may get extremly slow, like moving through honey.

In the end, you have a very powerful GUI API at your hands that does not at all have to look like the windows gui. Only two drawbacks:

1. directly in the gameplay, you need self-drawn controls (but these should be simplistic anyway, to remain usable without pausing the game), because

2. Don''t expect bitblt wouldn''t have an impact on your frame rate, compared to surface->Flip(). For background animations or a still visible animated game screen in the "menu mode" of your game, this won''t matter so much.

P.S. Don''t forget to Flip() your surfaces in case the primary one is hiden at the moment when you enter your "menu mode", for else no single windows control will be visible (yet they accept input). This can be a confusing bug, when in 50% of all cases everything works fine, in the other 50% not, and the only reaction your computer gives you is a "beep" when you accidentally click outside of the active "open file" dialog. I''ve seen this :-)

-- Smart Pointers remark:

Are you sure that is an official **PATTERN**? I thought the pattern was called "Bridge" aka "Handle-Body" and smart pointers were only a technique, an idiom at best, to achieve it.

I would not prefer to go around using smart pointers directly, with the exception of auto_ptr. I''d rather build a class library based on the Bridge Pattern, using a smart pointer template class to achieve this goal. Because when you''re freely using any kind of pointers just as seems fit, you are most certain to get in trouble. In this case, it''s hidden, never deleted refs (memory leaks) and, of course circular refs, if the smart ptr uses ref counting or ref linking (and it will, I assure you).

Of course, these are problems youre perfectly welcome when you use ref-type-like Bridge Pattern based classes, only the logic of what you''re doing will be far more obvious.

shadi

Share this post


Link to post
Share on other sites
quote:
Original post by shadi
Are you sure that is an official **PATTERN**?

What do you mean by "official"? Don''t fall into the trap of thinking the 23 patterns in the DP book are the only patterns in existence - that would be to deny the nature of patterns. But yes, Smart Pointer is a pattern. If you really insist on having a reference to an in-print publication, then POSA has the Counted Pointer pattern.
quote:

I thought the pattern was called "Bridge" aka "Handle-Body" and smart pointers were only a technique, an idiom at best, to achieve it.

An idiom *is a* pattern. Other than that, you''re correct that smart pointers are a form of handle-body, but note there are many names for such patterns, also including Cheshire Cat and pImpl. They''re all just variations on a theme (which is part of the nature of patterns), and there are not really "official" names - just common names.
quote:

I''d rather build a class library based on the Bridge Pattern, using a smart pointer template class to achieve this goal. Because when you''re freely using any kind of pointers just as seems fit, you are most certain to get in trouble.

Only if you use them inappropriately, and there''s probably less chance of doing that than there is of using a normal pointer inappropriately.

Share this post


Link to post
Share on other sites
Well, pImpl, or pimpl, as I prefer to call it, is just an extremely reduced form for reducing of compile time dependencies. My approach to smart ptrs is not to regard them as implementing the bridge pattern themselves.

I simply think, smart pointers are to the Bridge Pattern in general what the auto_ptr is to the pimpl idiom.

And for any other purpose there are better solutions, including auto_ptr, which is the only smart pointer that I would ever recommend for direct use outside of class design.

Using smart ptrs in collections is stupid.

On the stack? use auto_ptr.

For global data? There is no global data. singletons at best.

for notification? use soft refs if you have to, use softly ref''ing collections if available.

for manipulating raw memory byte- or wordwise? use native pointers. they won''t try to delete() that red pixel in the upper left corner of your screen when after you''ve been playing with raw directX surface data.

for passing fuctions as parameters? use Functors, maybe created from a function, holding a raw pointer that never has to be touched directly. even its construction will go without a ''*''.

I simply see no point in using smart pointers directly in late stages of software design. and even in early stages I try to put them at their proper place and hide them from my eyesight as soon as possible.

shadi

Share this post


Link to post
Share on other sites
quote:
Original post by shadi
Using smart ptrs in collections is stupid.

Please qualify this statement.
quote:

On the stack? use auto_ptr.

On the stack what? If you mean the pointee, then no, that would be an erroneous use of auto_ptr - you can''t delete something on the stack.

[snip tangential stuff]

quote:

I simply see no point in using smart pointers directly in late stages of software design. and even in early stages I try to put them at their proper place and hide them from my eyesight as soon as possible.

Quite simply, smart pointers should be preferred anywhere that a pointer is relevant to solve a problem. Boost''s smart pointers fill the glaring omission of shared_ptr and scoped_ptr from the Standard. If you don''t want to use smart pointers in your designs, that''s up to you. However, if you want to go around offering advice like "using smart pointers in collections is stupid", you need to explain why it is stupid.

Share this post


Link to post
Share on other sites
quote:
Original post by shadi
And for any other purpose there are better solutions, including auto_ptr, which is the only smart pointer that I would ever recommend for direct use outside of class design.

Golly.

I dunno about you, but auto_ptr is the smart pointer type I use least often, simply because destructive copy semantics are rarely what I want.

boost::scoped_array is handy, because it offers (IMHO) greater convenience than a vector for creating buffers, as well as smaller overheads.

boost::shared_[ptr, array] are useful because I can stick ''em in a collection without having to care about deleting the damn things.

quote:
Using smart ptrs in collections is stupid.

Yes, because it''s soooooooooooo much better to have to remember to delete the contents of your container each time you remove something, isn''t it?

:rolleyes:

quote:
On the stack? use auto_ptr.

Use auto_ptr for what? auto_ptr can''t point to arrays, and auto_ptr has annoying copy semantics.

quote:
for notification? use soft refs if you have to, use softly ref''ing collections if available.

I assume that by "soft" you mean "weak"? Weak references are just another kind of smart pointer....

quote:
for manipulating raw memory byte- or wordwise? use native pointers.

Uh... why?

quote:
they won''t try to delete() that red pixel in the upper left corner of your screen when after you''ve been playing with raw directX surface data.

Nor will a correctly-chosen smart pointer.

quote:
I simply see no point in using smart pointers directly in late stages of software design.

Then you must enjoy remembering where and when to call delete. I don''t; I have the tools to permit such lifetime management to be performed by the objects themselves, which frees me to concentrate on more interesting things.

quote:
and even in early stages I try to put them at their proper place and hide them from my eyesight as soon as possible.

:rolleyes:

All I can say is, you''re lucky to never have to work with C APIs. I dunno about you, but I often have to write things that look like:

size_t size = 0;
SomeLegacyAPI(NULL, &size);
boost::scoped_array buffer(new char[size]);
someLegacyAPI(buffer.get(), size);
// do something with buffer
size = SomeOtherLegacyAPI(size, NULL);
buffer.reset(new char[size]);
someOtherLegacyAPI(size, buffer.get());
// do something with new buffer
// etc.


Now, what do you propose I do instead?

I could use raw pointers... but to be honest, that''s a pain. I very rarely omit deletes, but I have done so at least twice in the past three years of professional programming.

I could use std::Vector<char>... but that''s got problems of its own. It''s not (yet) mandatory for it to use contiguous storage. And even if it were, the Defect Report doesn''t provide an acceptable answer. Reason being, it doesn''t consider alignment issues. The memory from new char[N]; is guaranteed to be suitably aligned for all types T such that sizeof(T) <= N. Even with the fixed (guaranteed contiguous) vector, that (stricter) requirement isn''t made. An implementation would be permitted to have &v[0] where v is a std::vector<char> be an address that''s aligned on a boundary unsuitable for some non-char type. In addition, I can''t easily shrink a vector. There is a common idiom to effect such a thing, however it''s not (yet) strictly correct; a Defect Report is pending, so once a library TC is created, the "correct" behaviour should be correct. In any case, the use of a vector is IMHO uglier (&buffer[0] vs. buffer.get(), vector<char>().swap(buffer) vs. buffer.reset(), etc.), and a vector certainly carries more overhead than a simple scoped_array.

Or, I could use boost::scoped_array, and be both guaranteed that I won''t leak and have simple syntax.

In the absence of any better solution (and, no, wrapping Win32 in a bunch of classes isn''t a better solution), smart pointers remain far and away the best way of doing things.

Share this post


Link to post
Share on other sites
quote:
Original post by MtSMox
Hi,

I''m currently working on a GUI. In it I have windows (duh...). Pointers to the window are shared throughout the program. But I have one problem. Those pointers are invalid when I delete the window. So I have to make something to let the other pointers know they''re invalid. That''s why I came up with the "Safe Pointers". But how to implement them.

It should be a class that lifes as long as there are pointers going on in the program to the window it points to. If something wants to delete the window it calls class.release() which makes the pointer invalid. But when to delete the class. And how to keep track of the pointers handed out?
Is there a certain design pattern for this?

thanks,
Mox


Hi

I maybe wrong here, what is the problem? if you are using dynamicmemoryallocation you also use deallocation. So why not set the pointer to 0 when deallocating. And maybe the delete does that jobb too.

Share this post


Link to post
Share on other sites
quote:
Original post by DrPizza
I dunno about you, but auto_ptr is the smart pointer type I use least often, simply because destructive copy semantics are rarely what I want.


I really don''t understand what''s the meaning for ''destructive copy semantics''?

Share this post


Link to post
Share on other sites
quote:
Original post by DerekSaw

I really don''t understand what''s the meaning for ''destructive copy semantics''?


Copying an auto_ptr breaks the original auto_ptr, because it loses ownership of the object.

Share this post


Link to post
Share on other sites
The Loki smart-pointer is extremely versatile, and can be tailored to work the way you want it to. (see sig for link)

auto_ptr is of limited scope, because it transfers ownership during assignment. It would not work well for the problem described in the original post.

...
Smart pointers are an idiom, not a design pattern.
Smart pointers are not practically applicable to environments that garbage collect - but all design patterns are applicable to their categorical programming environment (e.g. imperative or functional).

quote:

What do you mean by "official"? Don''t fall into the trap of thinking the 23 patterns in the DP book are the only patterns in existence - that would be to deny the nature of patterns. But yes, Smart Pointer is a pattern. If you really insist on having a reference to an in-print publication, then POSA has the Counted Pointer pattern.


{Smart Pointer} !U {Counted Pointer}
Smart pointers are not a subset of counter pointers, so even if one considers counted pointers a design pattern, that doesn''t mean all kinds of smart pointers, or smart-pointers (as a collective) are a design pattern.

I think the POSA''s definition of a pattern must be different than the GoF''s and different than Christopher Alexander''s. Which is fine, if they want to describe something different... counted pointers and visitors are not very close in their level of abstraction though.

Would we claim that the switch statement is in-fact an implementation of the jump-vector design pattern?


Magmai Kai Holmlor

"Oh, like you''ve never written buggy code" - Lee

[Look for information | GDNet Start Here | GDNet Search Tool | GDNet FAQ | MSDN RTF[L] | SGI STL Docs | STFW | Asking Smart Questions ]

[Free C++ Libraries | Boost | ACE | Loki | MTL | Blitz++ | wxWindows| Spirit(xBNF)]

Share this post


Link to post
Share on other sites
quote:
Original post by Magmai Kai Holmlor
Smart pointers are an idiom, not a design pattern.

Same thing, different term.
quote:

Smart pointers are not a subset of counter pointers

I didn't say they were. I was pointing out that there are two well-known patterns which would cover the reference-counted smart-pointer (most patterns have several different names, and there are many arguments about those names).
quote:

so even if one considers counted pointers a design pattern, that doesn't mean all kinds of smart pointers, or smart-pointers (as a collective) are a design pattern.

No, what defines them as a design pattern is that they are regularly occuring variations on a theme commonly used in resolving a particular set of design forces.
quote:

I think the POSA's definition of a pattern must be different than the GoF's and different than Christopher Alexander's.

It's not. The 23 patterns in GoF are *not* the only patterns in existence. *Anyone* is free to "invent" a design pattern, it just needs to adhere to the rather loose definition of what it means to be a design pattern. The keyword is "pattern" - if it is a commonly recurring pattern used in software system design, then it is a design pattern. There's no more to it than that.
quote:

Would we claim that the switch statement is in-fact an implementation of the jump-vector design pattern?

You could, but it is very well known as the switch statement.

[edited by - SabreMan on August 21, 2002 4:45:50 AM]

Share this post


Link to post
Share on other sites
ok, I will happily agree that there''s a huge number of good resrons for using smart pointers for a lot of things. But let''s not forget that smart pointers are still pointers and as such dangerous because they hide the logic of what you''re doing behind a technical detail. The risk of reference counted smart pointers is leaking memory and other resources, so it is preferable to hide every use of pointers inside a library and keep the interfaces free of them, IF POSSIBLE.

If the choice is C ptrs or ref c''ted smart ptrs, use the latter. This includes their use for implementation of the Bridge Pattern, which is clearly my favourite approach for writing GUI liraries, immutable string classes and the like. Basically, every class where sharing a single implementation might make sense (clearly excluding mutable string classes and their kindred).

As soon as you add any kind of ptr to a collection, the risk is high to forget about it later on. And such design tends to generating an awful lot of collections filled with pointers and will inevitably lead to all problems ptrs are capable of causing. The problem is, the logic of what you''re doing is again hidden behind ptrs. But luckily, there''s an approach where a hard reference to an object will only be contained in a list if the owner of the list owns the object and nowhere alse will ever another hard ref be stored. For purposes like event dispatching, automatized collections will be used that guarantee never to prolong the lifetime of any object the reference and also take responsibility for removing dead references and dispatching events to all still existing objects they reference, without having to let out NullReferenceExceptions :-)

The topic was writing a GUI library, and I think it is most easily done with shared implementation classes for windows and the like and at least one collection class, preferably a list wherein all references are implicitly weak for event handling purposes, so registering event handlers will not inevitably lead to circular references.
(there''s even situations in java where this might lead to memory leaks, not because of circularity, but because sometimes it''s pratical to add closable child windows as listeners to something references by the main window or even of longer lifetime for notification of general program state changes, thereby generating a second reference that will hinder garbage collection of the child window unless the programmer explicitly removes it from all event listener lists manually)


So, feel free to use smart pointers whenever it makes life easier when necessary. But for designing a GUI or other class library there''s a lot of better ways one of which I was just trying to outline.


** alignment of "vector":

As far as I know the standard demands from vectors both use of contigous memory (else it would at best be a deque) AND correct alignment, practically forcing STL implementors to use C++ arrays on the free store (using new[]), and older compilers also tend to implement them like this way because it''s easier anyway. I think I''ve got this from Herb Sutter''s "More Exceptional C++", but I would have to take another look to be sure.

shadi

Share this post


Link to post
Share on other sites
quote:
Original post by shadi
But let''s not forget that smart pointers are still pointers and as such dangerous because they hide the logic of what you''re doing behind a technical detail.

This is called *abstraction* and is something to aim for, not to avoid. What exactly is the danger of not exposing a library user to the internal complexity of the library? That they might be able to concentrate on *their* problem?
quote:

The risk of reference counted smart pointers is leaking memory and other resources

How so? Please provide a code sample or clear description of how this would happen with a *correctly operating* counted pointer.
quote:

so it is preferable to hide every use of pointers inside a library and keep the interfaces free of them, IF POSSIBLE.

That statement might be true, but the way you arrived at it is erroneous.
quote:

As soon as you add any kind of ptr to a collection, the risk is high to forget about it later on.

Forgetting about it is exactly what I want to do, since I am happy for the collection to take down everything it owns when it goes out of scope.
quote:

And such design tends to generating an awful lot of collections filled with pointers and will inevitably lead to all problems ptrs are capable of causing.

Huh? You''re missing a fairly important point here. To achieve polymorphic behaviour in C++, you have to go through a pointer or a reference. Since references cannot be stored in collections, that means pointers are the only option. Additionally, pointers are the only means of sharing objects in different collections.

Use of a good smart pointer will not "inevitably lead to all problems ptrs are capable of causing", since the very reason for the existence of smart pointers is to avoid many of those problems.
quote:

The problem is, the logic of what you''re doing is again hidden behind ptrs.

So what? I never heard a Java or Lisp programmer say "I need to see the pointer".
quote:

For purposes like event dispatching, automatized collections will be used that guarantee never to prolong the lifetime of any object the reference and also take responsibility for removing dead references and dispatching events to all still existing objects they reference, without having to let out NullReferenceExceptions

Are we even talking about the same language?
quote:

So, feel free to use smart pointers whenever it makes life easier when necessary.

Which is almost anytime a pointer is the solution to a problem (unless a reference is suited).
quote:

As far as I know the standard demands from vectors both use of contigous memory

No it doesn''t.
quote:

(else it would at best be a deque)

No it wouldn''t. It would be a vector with no guarantee of contiguous storage. Having said that, I don''t think there''s any compilers which implement any other way (than contiguously).

Share this post


Link to post
Share on other sites
quote:
So what? I never heard a Java or Lisp programmer say "I need to see the pointer".

Java programmers use pointers whenever they create an object. Sun calls them references, but their behaviour is pointer-like, not reference-like.




quote:
As far as I know the standard demands from vectors both use of contigous memory

Nope.

There''s a defect report on the issue, but it''s not demanded by the standard. You did bother to click the hyperlinks in my post, didn''t you? I wasn''t just making it up.

quote:
(else it would at best be a deque)

The current standard would permit a vector to be implemented identically to a deque. The deque has better properties in a number of regards (no pointer invalidation on resizing), but that doesn''t matter.

quote:
AND correct alignment,

There is an implicit requirement that the alignment is suitable for the contained objects. But there is no requirement, as far as I can see, for a vector<char> to provide memory that is suitably aligned for any object which can fit into the vector (i.e. it doesn''t have the same constraint as memory directly obtained from new has).

quote:
practically forcing STL implementors to use C++ arrays on the free store (using new[]), and older compilers also tend to implement them like this way because it''s easier anyway.

I''m sure they do. The point is, they are not currently required to do so, and, further, even when a library TC is released, the alignment issue will, as far as I can tell, persist.

quote:
I think I''ve got this from Herb Sutter''s "More Exceptional C++", but I would have to take another look to be sure.

I''m quite sure that Herb Sutter made no such claim, as I''m sure he knows of the disparity between the current standard and the intended behaviour.

Share this post


Link to post
Share on other sites
quote:
Original post by DrPizza
Java programmers use pointers whenever they create an object. Sun calls them references, but their behaviour is pointer-like, not reference-like.

Yes, that was my, err.. point. I don''t hear Java programmers saying "oh no, my logic is hidden behind a pointer, whatever shall I do". BTW, there''s only a difference between pointer-like and reference-like in C++, as it''s the only language, AFAIK, which has weird references.

Share this post


Link to post
Share on other sites
quote:
Original post by SabreMan
Yes, that was my, err.. point. I don''t hear Java programmers saying "oh no, my logic is hidden behind a pointer, whatever shall I do".

But they wouldn''t have to, since they deal with pointers all the time (even if they don''t know it) -- they won''t say "I need to see the pointer" because they can already see it. Unlike, say, a lisp programmer.

quote:
BTW, there''s only a difference between pointer-like and reference-like in C++, as it''s the only language, AFAIK, which has weird references.

I''m pretty sure that languages that offer objects on a GC heap and default to pass-by-pointer-value but also offer pass-by-reference exhibit similar distinctions.

I''m not sure how C++''s references are "weird", btw.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Dear SabreMan (Säbelmann)

I am very sorry for having used the word logic in its exact opposite meaning. I meant "it hides the IDEA of what you''re doing behind a technical detail" (pointers).

The problem is, I used the word "logic" as I would have used the german word "Logik" which almost always means the idea and not the technical implementation. We would say in german, "Implementierungsdetails" (details of implementation, would be self explanatory if it wasn''t written as one extremely large word), rather than "Logik" to indicate the internals of what''s happening (including pointers and such)


You want an example of a situation where reference smart pointers leak memory? Every time a method or function internally stores a ref counted smart pointer in a list, like for event dispatching through functors themselves holding such a ptr to the original object, its lifetime might be prolonged because it will live until the last one of the smart ptrs goes out of scope, not the "relevant" one. This same applies to garbage collected languages, like java. And the solution is the same:
If you''re writing a library, automatize these things so the poor programmer won''t have to think of removing no-longer-needed references from whereever they might exist. weak references are a good solution, as long as their storage for this purpose is automatized by a specialized collection class.

Yes, we are speaking of the same language. As soon as weak references are possible, some kind of NullException or null_pointer_exception class is necessary. Polymorphism only demands that both the outer class and the impl class are derived simultaneousley. polymorphism works fine because it is fully realized by passing const references in cpy ctor and op=.

shadi

Share this post


Link to post
Share on other sites
not "reference smart pointers" but "reference COUNTED smart pointers", of course.

the automatized collections I was speaking of have the main purpose of storing weak pointers for event dispatching

shadi

Share this post


Link to post
Share on other sites


using namespace MyGUILib;

void onMouseClick(const MouseEvent&);


int APIENTRY WinMain(HINSTANCE hinst,HINSTANCE,LPSZSTR,INT) {

FrameWindow w(hinst);

object o=w;

static_cast(o).whenclickedon().add(f);

vector v(10); // might throw an exception
v[0]=w;

static_cast(v[0]).whenclickedon().add(onMouseClick);

MouseEventFunctor f=somegenerator();
w.clicked().add(f);

return f.main_loop();

}


no pointers :-)

yes, this is c++

shadi

Share this post


Link to post
Share on other sites

Important Information

By using GameDev.net, you agree to our Terms of Use and Guidelines.

Create an account with GameDev.net and join the game development conversation on our forums, blogs, articles, and more!

Sign me up!