Tom Lachecki

(Tomalak Geret'kal)


One Less Bug To Worry About

From the MySQL documentation on LAST_INSERT_ID() and AUTO_INCREMENT columns:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

So, I've spent years panicking about race conditions in code like that below that apparently won't exist (at least in my cases):

`tbl`
------------------------
`id`  INT AUTO_INCREMENT
`col` TEXT

INSERT INTO `tbl` (`col`) VALUES("lol");
SELECT LAST_INSERT_ID(); -- get `id` for inserted row

Perhaps you have, too?


Update

This is not explicitly the case for SQL_CALC_FOUND_ROWS and FOUND_ROWS(), though the following paragraph loosely implies that FOUND_ROWS() is guaranteed to be ok after SQL_CALC_FOUND_ROWS, at least within the same connection context:

The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement

Tags: , ,
Permalink | No Comments  
Debunking Leitner

C++ is complex. Very complex. Some say that it is far too complex, and I'm going to neither agree nor disagree with that here. That's not what this post is about.

I was linked earlier on to a presentation entitled "The Dark Side Of C++", written in August 2007 by C expert Felix von Leitner. He attempts to explain C++'s pitfalls and demonstrate why a programmer should choose another language. Though the intention is sound and some good points are made, unfortunately it also contains untruths. Therefore, I shall go through parts of the presentation, debunking its lies.

Again, I'm not doing this to defend C++. I'm actually doing it to defend any language newcomers who may stumble across this dangerous misinformation and believe it to be true, because it is not.

I am not going to go out of my way to point out areas that I agree with. (In particular, the implementation of library features does lead to some utterly horrendous diagnostic output.)


Slide 7

This slide is entitled "ever-changing standard", then lists the following ways in which the standard allegedly changed:

  • Wrote commercial C++ app in 1997
  • Then C++ changed (life time of i in "for (int i=0; …)")
  • Then C++ changed again (use iostream instead of iostream.h)
  • Then C++ changed AGAIN (namespaces)

Useless maintenance work. Would have been less trouble in C.

In fact, C++ was standardised in 1998, and all of these elements were fixed in place at that time. To this day, none of them have ever changed in the standard. The "useless maintenance work" would have been less trouble had Leitner actually written standard C++.

Slide 8

Old and busted:
for (int i = 0; i < n; i++)
New hotness:
for (int i(0); i != n; ++i)

Convention and idioms are important. If we all agree basically how to code, then cross-maintenance becomes easier.

However, this difference in construction syntax never really took off. Both are valid, and there is no consensus at all that the second approach is the "new hotness"; in fact, I don't think that I've ever seen it in production code.

Slide 12: "C++ is hard to parse"

struct a{typedef int foo;};struct a1:a{};struct a2:a{};
#define X(b,a) struct a##1:b##1,b##2{};struct a##2:b##1,b##2{};
X(a,b)X(b,c)X(c,d)X(d,e)X(e,f)X(f,g)X(g,h)X(h,i)X(i,j)X(j,k)X(k,l)
X(l,m)X(m,n) n1::foo main(){}`

I'm not convinced that you can just throw up a ridiculously retarded piece of code like this, and use it as proof of a language flaw. When would you write this? Well-written C++ code is reasonably easy to parse (sometimes).

Slide 15: "C++ is hard to write"

  • Can't throw exceptions in destructors, shouldn't in constructors

You can throw exceptions in destructors (though you shouldn't).
Throwing in constructors is fine; the default allocator throws bad_alloc, for goodness's sake.

  • Initializers done in order of declaration of fields in class, not written order

Good. I can't imagine having to figure out where the implicitly-constructed ones would go in an incomplete member-initialiser were the order not concretely defined.

  • auto_ptr is useless

I can't disagree with that, and in fact auto_ptr has been deprecated in C++0x.

  • Iterators don't know anything about the container, can't detect errors
  • For a vector, at() does bounds checking, but operator[] doesn't
  • Can't call virtual member functions from constructor or destructor

Again, these are all good things.

Slide 16: "Throwing exceptions from con/destructors"

My personal favourite, this slide is full of utter nonsense.

  • Exceptions in constructor don’t unwind the constructor itself
  • Does not even clean up local variables!
  • Must do own cleanup

This is a flat-out lie. When throwing from a function, even a "special function" like constructors, any local objects are destroyed just as they would when going out of scope anywhere else.

#include 
#include 

using std::cout;
using std::logic_error;

struct Tracked {
   Tracked() { cout << "*"; }
  ~Tracked() { cout << "~"; }
};

struct Test {
   Test() {
      Tracked t;
      throw logic_error("Yes, it *is* unwound. Things go out of scope as usual.");
   }
};

int main() {
   try {
      Test t;
   }
   catch (...) {}
}

// *~

Live demo.

  • OTOH: no other way to return failure, constructors are void

Constructors are not void. They are constructors.

Slide 20: "Bounds Checking"

  • For a vector, at() does bounds checking
  • operator[] can, but does not have to
  • The one from gcc doesn’t

Good. Then I have an option when I don't need the overhead of bounds checking. C arrays don't have bounds checking.

Slide 21: "Virtual functions in con/destructor"

  • In the constructor, the vtable is not properly initialized

That would be the virtual pointer. The vtable exists since compile-time. This is an implementation detail though: C++ as a language has no knowledge of either.

  • Usually, function pointers in vtable still point to virtual member of base class
  • ... which can be pure virtual

This is a lot more useful than the automatic this pointer referring to an object that does not yet exist. Remember, when the Base part is being constructed, the Derived part hasn't started being constructed yet.

  • In the destructor of the base class, vtable points to base class

Similarly, it would be incredibly awkward to work around a virtual dispatch mechanism that tried to use the already-destroyed part of an object as you're cleaning it up.

Slide 37: "Other Nitpicks"

  • Can't tell what exceptions a library can throw

You can, by looking at the documentation. This is no different from the manner in which you find out anything else about library functions.

Slide 39: "Exception Safety"

If new[] throws an exception, this leaks a file handle and deadlocks the next caller.

That's only because Leitner is writing C-style code. He has not used the principle of RAII and insists on using antiquated C library functions rather than file streams, and this is the cause of his problem. Using C++ conventions and idioms completely nullifies this issue.

Slide 47: "Pointer arithmetic with base classes"

This slides presents an example of attempting to use non-polymorphic classes polymorphically. Just don't do that then.

Slide 48: "Gratuitous Bjarne Quote at the end"

Whole program analysis (WPA) can be used to eliminate unused virtual function tables and RTTI data. Such analysis is particularly suitable for relatively small programs that do not use dynamic linking.

No shit, Sherlock.
It will be ready right after Duke Nukem Forever runs on the Hurd.

Microsoft Visual Studio has supported this since at least two years before the publication of this presentation and, as far as I'm aware, the recently released Duke Nukem Forever is not yet available on the GNU Hurd platform.


Now, don't get me wrong. As I said before, Leitner makes some valid points, and the overarching message that C++ is overly complex and confusing in certain places is certainly not without merit.

So go ahead and read his presentation... just keep a copy of this article with you throughout.

Tags:
Permalink | [3] Comments  
Canning Circus Police Station

I went out for the evening and came back to find reports that Canning Circus police station — which is 30m across the road from my flat — had been "firebombed".

On personal inspection I found a mildly shattered window, a thin stretch of cordon and two police officers standing guard at the entrance. No sign of fire damage, though it is dark and I have been drinking slightly.

I did notice that a Toyota dealership half a mile away had moved its entire stock of vehicles to a secure compound, but otherwise I can't see anything particularly interesting going on here. Frankly, for all the rap the Nottingham gets for crime, when it comes to mass organised unrest like we've seen over the past couple of days, I can't envisage anything particularly damaging going on here.

Nottingham is still very much a city where major crime is restricted to a specific few outlying areas. The media usually like to ignore this for reasons of sensationalism, but given what's going on elsewhere this week, these usually overblown activities are completely outdone by events elsewhere, and I don't see that changing tonight.


Update (midnight) Captions like this make me wonder how hyped-up the mainstream news is being. Honestly, there's not that much going on here.

(Though the live video report is from Manchester, the caption does relate to Nottingham.)


Update (00:23): There is quite a lot of siren action going on outside, but from what I can tell there's still not much going on here.

Tags: ,
Permalink | No Comments  
On The Riots; What Else?

As the assorted peoples of the internet gather around Facebook, Twitter and the rest of them watching violence unfold in several major English cities, a couple of things cross my mind. And let's be honest about them.

Population Quantity

The first is that the situation is utterly out of control, and that this is not really the police's fault. Not only have their numbers been drastically cut in recent years, but ultimately there are too many people in the country to control effectively when the shit hits the fan like this.

On a non-violent but wholly more spectacular scale, trying to keep up with the sheer volume of status updates, photos and amateur editorials (yes, yes, I know) is utterly impossible. Facebook groups demanding that the government listen to them are pointless, as it is not humanly possible to track — let alone respond to — the thousands of updates posted every 30 seconds or so.

Ultimately this is an argument for devolving power to local communities, something that the coalition government has always been in favour of. Personally, I think that more drastic steps are necessary: are we starting to see the fallout of encouraging globalisation alongside a decades-long population boom? Will democracy and "equal representation" now finally be crushed under its own weight? How can you represent, let alone control, sixty million people from a room that seats just thirty-three?

Population Quality

The second issue that comes to mind is that of who is out there committing this violence. Who are the gangs of "hooded youths" swaggering up and down the streets of the capital, trousers at their ankles, showing us that England's equivalent of Egypt's fighting for freedom is fighting for a free telly?

The truth is that they are simply the underlying current of society, the tax-reliant chavs and bored malcontents that scream by you on their bikes day after day, blaring trash out of their Blackberries. Usually their widely-reported criminal activities are limited to shootings in gangland areas and the occasional bout of bravery in a more "civilised" part of town, but it only takes a few to spread courage. And that entire subculture has now spontaneously erupted into a mob with sufficient courage to run around and do exactly what they were always capable of. It's not that the coalition Government in particular has failed them (why should these kids give a flying frak who the Prime Minister is?) or that Twitter/BBM is destroying our children: it's just that far too many parents from the 90s didn't raise their children properly, and now there are too many to control.

How about this: shoot them. Just… shoot them.

The really scary thing is that, though an article like this might have been mildly controversial ten years ago, I reckon that people are kind of starting to get the point now. (Even if I am being tongue-in-cheek… slightly. Maybe.)

Bootnote

In the words of James Corden's Craig, I never saw the point in London. I generally avoid trips there, probably for no good reason.

But frankly, tonight, part of me wants to go down there and help out the thousands of law-abiding citizens who seem to be properly banding together to defend their homes and businesses, and who are preparing to clean the damned place up in the morning. Odd though it is, the whole situation is actually creating something hugely positive on the other side of the coin: a "community spirit" that's pretty rare nowadays.

Realistically, I have work in the morning. What would be really cool, though, is if those law-abiding citizens could do me a favour, find the little chaps who burned down somebody's dearly loved 100-year old family-run furniture shop, and stab them repeatedly in the genitals with a flaming dagger made of coarse diamonds. That'd be great. Cheers.


Oh, and whilst I'm at it (and I do realise that I'm being a complete hypocrite here in a sense), whilst I'm grateful for the fantastic live coverage from the BBC and from Sky News, what we really need is a media blackout. Twerps aren't quite so loud when nobody's listening, surely.

And I have no comment about the "we're getting our taxes back, innet" lady, except… no. No, you're not.

Tags: ,
Permalink | 1 Comment  
On Festivals And Music

I went to Nottingham's Riverside Festival today, and it was astounding. Not just from the number of individuals present — from all walks of life — but from the talent that it demonstrated.

To put things into context, the Riverside Festival is a free, city council-run event that shows up every year along the riverbank at the start of August, featuring the standard funfair pieces, introducing slick, well-run and reasonably-priced licensed waterside bars (and that's hard to find at big events) and, above all, entertaining with some pretty quality music.

It's a multi-day event but, for the first time since setting foot in town six years ago, I decided to show my face on Saturday afternoon. My main target was the Monument Stage for an hour-long set by Maniere Des Bohemiens, a hauntingly talented group who will prance around on stage and fill your soul with Gypsy Jazz by means of several guitars, a clarinet, a violin and some brilliant percussion. This evening they also brought on stage a rather sensual Russian vocalist who served to complement the line-up and make the entire experience even more special.

I've wanted to see them live for years.

Then, having failed to find anything else to do with my Saturday evening (woah betide me, et cetera), I decided to stick around and give a chance to the next group to grace the Memorial Stage. That was Fat Digester who, for the ensuing hour or so, transformed my week completely with just the most amazing wall of sound I've ever heard. Blending soul and rock, this group had several hundred people swaying from side to side by the River Trent as a triple rainbow hung ominously overhead.

And it got me thinking. Why do we, as a culture, instead celebrate the most amazingly formulaic rubbish that we've ever heard?

Do I mean Fat Digester? Do I frak. I'm talking about the tracks that we hear in the official Top 40 charts every single week. Popular rubbish like Cher Lloyd's "Swagger Jagger" — near-universally loathed — and Rebecca Black's "Friday" — globally considered "the worst song ever" — take millions of pounds in sales every single week in the UK.

Now, Black's success is purely a function of fame, and of humanity's natural predisposition to following the crowd (see: Justin Bieber). And, in Cher's defence, she did not write that song.

But isn't that the problem? The vast majority of "popular" music today is a product of the Simon Cowells and the Jay-Zs, millionaire producers throwing re-used trash at money-hungry, semi-talented youngsters, eager for a piece of the limelight.

And what happens to the Maniere Des Bohemiens and the Fat Digesters of the world? Those groups who create their own brilliant sound and who are, regardless of your personal tastes, 100% talent? They are relegated to — amazing though the event is — a local festival of .. maybe .. a hundred thousand.

As I sit here, now back home, listening to the fantastic Ladytron at 1am on a Saturday night, it almost makes me physically ill to imagine how many genuinely talented groups and individuals are out there, struggling to be heard and to make a living, fighting against an established commercial industry whose primary motive is to put people on TV and bribe the lowest common denominator into buying their "music" week after week. It's hard to imagine that even a quarter of the population of the UK is even aware that there is more out there than Lady Gaga and Katy Perry.

And this is deeply, deeply distressing… made better only by the knowledge that real music does still exist. If you want to hear some, attend your local festivals. It'll be worth it; I promise.


Nottingham's Riverside Festival continues Sunday until 6.30pm.

Images reproduced without permission. Sorry. Please grant me it anyway!

Tags:
Permalink | [2] Comments