Ah – The One Definition Rule

In response to Scott Meyers’ question on non-inline non-template functions and the one-definition rule, Francis Glassborow replied with a very interesting example of two lexically identical functions that weren’t actually identical.
Try to find the difference:

1
2
3
4
5
6
7
// in file 1:
#include
#include
static int i(0);
void f() {
    std::cout << i;
}
1
2
3
4
5
6
7
// in file 2:
#include
#include
static int i(0);
void f() {
    std::cout << i;
}

The difference between the two, of course, is that the two functions do not refer to the same instance of i: each translation unit has its own definition and, as such, each version of f refers to its own version of i.

When reading this thread on comp.std.c++, this post convinced me that mr Meyers may well have under-estimated the complexity of what he proposed – and that the one definition rule is likely one of the hardest rules to cope with – and one of the rules one is most likely to stumble upon by accident if one doesn’t conciously avoid it – in the C++ programming language.

Share in top social networks!

About rlc

Software Analyst in embedded systems and C++ programmer. I specialize in systems design, concurrency and language design, and am interested in generic meta-programming and functional programming and their practical applications. I take a pragmatic approach to project management, focusing on the management of risk. I have over a decade of experience as a software professional and a background in science.
This entry was posted in C & C++, Software Design. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">