Skip to content

Clever Code

Showcase your best code, your most elegant solution, or your most hard fought subtle bug you've found and fixed

This category can be followed from the open social web via the handle clever-code@forum.codeproject.com

361 Topics 3.2k Posts
  • Ominous bug from DLL world [modified]

    c++ json performance help question
    30
    0 Votes
    30 Posts
    25 Views
    J
    I am equally perplexed. On the other hand, VC6's implementation of STL isn't the hottest either. Have you tried STL Port?[^] -- Kein Mitleid Für Die Mehrheit
  • Template Bug [modified]

    help performance
    7
    0 Votes
    7 Posts
    3 Views
    P
    Yes, I've had a few of those, and only recently did I figure out why. Live and learn, as they say. I would argue though that this is *less* dangerous than when a base implementation of the virtual function exists. Less subtle anyway. The vft is all set up by the time the constructor starts executing by the way, but it always gets passed a pointer to the one for the base class, even when you are constructing a derived object. The reason that Bjorn and his mates decided to do things this way is that the constructor of the derived class runs *after* that of the base class, so the derived object is in an unknown state (specifically, its instance variables will all be garbage) while the base class constructor is executing. Which brings me to yet another hobby horse of mine. The world would be (for me) a much (well, ok, slightly) happier place if you could say something like: class MyClass = 0 { ... }; Meaning: set all my instance variables to zero before you call the constructor. So simple! Why on earth didn't they think of that? Or am I missing something obvious? I believe C# does precisely this, whether you want it to or not. Only reason not to is efficiency I guess, but since Joe Programmer is going to painstakingly initialise them all (to zero, mostly) one-by-one anyway, that doesn't really wash. It's the little things that make a difference, I always think. Paul Sanders http://www.alpinesoft.co.uk
  • 0 Votes
    11 Posts
    5 Views
    P
    OK, here's my collection of horrible hacks. The hWnd parameter is the window you have just resized. hPaintWnd is the window you are going to draw into. On XP, these can be the same (but not under Aero). gIsXP is false on Windows 2000 (where PrintWindow is not supported), true on XP and Vista. The rest you already know. GetRelativeWindowRect is the most useful helper function I ever wrote, by the way. Good luck! #ifndef PW_CLIENTONLY #define PW_CLIENTONLY 0x00000001 #endif . extern "C" { typedef WINUSERAPI BOOL (WINAPI * tPrintWindow) (HWND hwnd, HDC hdcBlt, UINT nFlags); } . // GradientWindow::SmoothUpdate - repaint this window without flicker void GradientWindow::SmoothUpdate (HWND hWnd, HWND hPaintWnd) { if (!IsWindowVisible (hWnd)) // but beware WM_SETREDRAW (TRUE) return; . RECT wr; wr.left = wr.top = 0; if (hWnd != hPaintWnd) GetRelativeWindowRect (hWnd, hPaintWnd, &wr); hWnd = hPaintWnd; . RECT ur; GetClientRect (hWnd, &ur); ValidateRect (hWnd, &ur); . int width = ur.right; int height = ur.bottom; . RECT r; GetWindowRect (hWnd, &r); POINT pt = { 0 }; ScreenToClient (hWnd, &pt); int x_offset = -pt.x - r.left; int y_offset = -pt.y - r.top; width += x_offset; height += y_offset; . for ( ; ; ) { DWORD style = GetWindowLong (hPaintWnd, GWL_STYLE); if ((style & WS_CHILD) == 0) break; HWND hParent = GetParent (hPaintWnd); // else Aero doesn't draw if (hParent == NULL) break; hPaintWnd = hParent; } . HDC hDC = GetDC (hPaintWnd); assert (hDC); wr.left = wr.top = 0; if (hWnd != hPaintWnd) GetRelativeWindowRect (hWnd, hPaintWnd, &wr); . HDC hMemDC = CreateCompatibleDC (hDC); assert (hMemDC); HBITMAP hBitmap = CreateCompatibleBitmap (hDC, width + wr.left, height + wr.top); assert (hBitmap); HBITMAP hOldBitmap = (HBITMAP) SelectObject (hMemDC, hBitmap); . // We prefer not to use WM_PRINT because: // (a) it does not paint themed window borders correctly // (b) URLControl's don't highlight the selected text // (c) brush origin problems on Windows 2000 (but no gradients there anymore, so OK) if (!gIsXP) // no PrintWindow () on Windows 2000 SendMessage (hWnd, WM_PRINT, (WPARAM) hMemDC, PRF_ERASEBKGND | PR
  • Initialising a stack for a new thread

    data-structures
    9
    0 Votes
    9 Posts
    6 Views
    G
    Coding Bugs: It's What's For Dinner!™ Software Zen: delete this; Fold With Us![^]
  • Thanks for the missing warning

    game-dev help
    18
    0 Votes
    18 Posts
    8 Views
    N
    This makes sense, of course, but I have always thought that it would be really cool to have a "smart" = operator that, depending on context, is either comparison or assignment; a dedicated := assignment operator for when you're returning the result of an assignment; and a dedicated == operator for when you really want to compare. That way, you won't get bit, but you can have C's power if you need it. I'm not sure why no languages I've seen have this.
  • What's News? [modified]

    csharp asp-net com question announcement
    6
    0 Votes
    6 Posts
    4 Views
    P
    Brady Kelly wrote: I went for a beer to sustain me for the night. Then I ran into this crap and found more beers in the fridge. :laugh: That's understandable, been there, done that :) "The clue train passed his station without stopping." - John Simmons / outlaw programmer "Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon "Not only do you continue to babble nonsense, you can't even correctly remember the nonsense you babbled just minutes ago." - Rob Graham
  • Off-Code Errors?

    help database testing business beta-testing
    8
    0 Votes
    8 Posts
    4 Views
    M
    :laugh:
  • It is not a bug

    help
    2
    0 Votes
    2 Posts
    2 Views
    P
    I thought it was pretty common knowledge that varchar without length specification was default to one character, not really a subtle bug :suss: "The clue train passed his station without stopping." - John Simmons / outlaw programmer "Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon
  • Creating two random arrays

    help debugging lounge
    17
    0 Votes
    17 Posts
    7 Views
    M
    Singletons started out as a workaround for a C++ issue: that you can't control the order that static objects are initialised in that environment. .NET static constructors are guaranteed to be run at the first access to any static or instance field of the type, or the first invocation of any static, instance, or virtual method of the type (that's nearly a direct quote from the CLI spec). To all intents, singletons are global variables. Make life easier on your clients: use a static class with a static constructor and static methods to implement your 'singleton'. DoEvents: Generating unexpected recursion since 1991
  • C - address of a pointer

    lounge
    14
    0 Votes
    14 Posts
    5 Views
    M
    Paul Conrad wrote: tried a 8 pound one, it just bounced off the concrete Amateurs! :) [Genetic Algorithm Library]
  • The classic Case bug

    c++ com architecture help
    29
    0 Votes
    29 Posts
    28 Views
    R
    Nemanja Trifunovic wrote: In fact, C syntax sucks in general - why do all these "new" and "clean" languages keep it when they don't aim for the source-level compatibility with C? You'd be surprised how important familiarity can be.
  • VS 2008 Debugger going crazy?

    debugging visual-studio com regex question
    12
    0 Votes
    12 Posts
    8 Views
    M
    Judging by the screenshot, I assumed VS would open the watch windows by itself ;P Anyway, for my it just crashed after opening what was apparently one too many of these watch windows. I did have other cases where something similar happened, but I don't think I have still have the code, it's already fixed.
  • VS2003 and const

    csharp visual-studio sales help learning
    5
    0 Votes
    5 Posts
    2 Views
    K
    It's happened to me with VS 2005 a few times. Kevin
  • 0 Votes
    11 Posts
    7 Views
    J
    I found your answer quite smart so I decided to try: if(!l_odtnProductsProductDiscountComponents.TryGetValue(p_intProductID, out l_ocltProductProductDiscountComponents)) { //extra curly brace lock(l_odtnProductsProductDiscountComponents) if(!l_odtnProductsProductDiscountComponents.TryGetValue(p_intProductID, out l_ocltProductProductDiscountComponents)) { l_ocltProductProductDiscountComponents = new Collection<ProductDiscountComponent>(); for(int i=0;i<this.Count;i++) //suggested code { //suggested code ProductDiscountComponent l_oProductDiscountComponent = this.GetItem(i); //suggested code if(l_oProductDiscountComponent.PriceListID == p_intPriceListID) //suggested code if(l_oProductDiscountComponent.ProductID == p_intProductID) //suggested code l_ocltProductProductDiscountComponents.Add(l_oProductDiscountComponent); //suggested code } //suggested code //foreach(ProductDiscountComponent l_oProductDiscountComponent in this) //original code // if(l_oProductDiscountComponent.PriceListID == p_intPriceListID) //original code // if(l_oProductDiscountComponent.ProductID == p_intProductID) //original code // l_ocltProductProductDiscountComponents.Add(l_oProductDiscountComponent); //original code l_odtnProductsProductDiscountComponents.Add(p_intProductID, l_ocltProductProductDiscountComponents); } } //extra curly brace Of course it still compiles just fine:) Sadly, when removing the 'extra' curly braces the compiler still encounters the internal error. In the error list just before/above the internal compiler error the compiler reports 2 'normal' errors; Warning as Error: The variable 'i' is declared but never used Warning as Error: The variable 'l_oProductDiscountComponent' is declared but never used In the original situation (foreach version) only the 2nd of the above errors appeared, logically. For clarity I would like to state that the code with the extra curly braces, which compiles fine, also produces the expected results. Thanks, Victor, for your interesting suggestion though. If you'd like me to do any more tests/adjustments, perhaps even scarier stuff like gathering IL or preprocessed source, I'm willing to go on with this for a while. With the more technical stuff I do need proper guidance though.
  • Spring is here!

    database help java sysadmin algorithms
    12
    0 Votes
    12 Posts
    7 Views
    P
    dan neely wrote: getting burned by daylight savings shifts certainly seems like s subtle bug to me. I agree. This is July and I am finally getting used to it :-\ "The clue train passed his station without stopping." - John Simmons / outlaw programmer "Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon
  • Problem taken from a C++ quiz

    question c++ com help tutorial
    25
    0 Votes
    25 Posts
    35 Views
    M
    Stuff like that pisses me off. Might be bad experience, but teachers often feel funny and think they come up with a "good" way of testing the students' knowledge with excessively nested or obscure code. The main reason why it pisses me off is because stuff like that usually never got mentioned before in class. Not even once. Not only that, usually none of the resources mention it either. So the students not only have no reason to ever use something like that, they usually don't even know something like that is even possible. This means they have no idea just what the hell will happen. Thinking it through won't help either because it's not something you can deduct from the stuff you learned, it's only a 50/50 guess whether you get the right answer or not. Might be just my bad experience but I've written too many tests where the larger part was made up of questions like that and the things you really discussed in class and read in the resources made up less than half of it. It was more like guessing the right answers rather than testing the acquired knowledge.
  • Firefox vs IE

    beta-testing csharp javascript visual-studio testing
    12
    0 Votes
    12 Posts
    6 Views
    S
    Ariel Kazeed wrote: Which means Windows Update is outdated for, as far as I know, neither MacOSX or any linux distribution needs a browser add-on for updating. How do you figure that? On Windows Update (http://windowsupdate.microsoft.com/[^]) the browser can access the system and display which updates you need. Read that last part again: the browser, not another system component or a downloaded application, but the browser. The browser doesn't just display a list of updates, it examines your system and only shows what you need. Things such as OS version, installed software and installed devices all may effect this filtering. The ActiveX control is only there to integrate that functionality into the browser. If you schedule an update no ActiveX is needed, for example. You don't seem to have a grasp of the issues involved. Steve
  • 0 Votes
    9 Posts
    5 Views
    S
    I bet the refactorer thought they were being really clever with the XOR trick. Not clever changing working code unless you've got a really good reason. I doubt the performance would've improved much either.
  • Not all roads lead to rome...

    csharp help question discussion
    7
    0 Votes
    7 Posts
    3 Views
    S
    mav.northwind wrote: I was hoping for a link about document information in RTF documents... That wouldn't be much use, they change them daily in an attempt to make Google look bad!
  • My weirdest error message ever.

    help csharp visual-studio testing beta-testing
    7
    0 Votes
    7 Posts
    6 Views
    M
    :) Sounds like self-sabotage. My weirdest error message ever was in VBA, an empty message box. Highly informative, I can assure you. :doh: Or another time I just got "400". Whether it was some error code or the content of a random variable I probably won't ever find out. Not that I'd care aynway...