Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C++'s <vector> templated class doesn't break one definition rule?

Maybe its lame question, But I don't get it! If I include <string> or <vector> in multiple translation units (different .cpp) why it doesn't break the ODR? As far as I know each .cpp is compiled differently so vector's methods code will be generated for each object file separately, right? So linker should detect it and complain. Even If it won't (I suspect it's special case for templates) will it be using one code or different set of cloned code in each unit, when I link all together???

like image 235
barney Avatar asked Dec 31 '15 23:12

barney


2 Answers

The same way any template definitions don't break the ODR — the ODR specifically says that template definitions may be duplicated across translation units, as long as they are literally duplicates (and, since they are duplicates, no conflict or ambiguity is possible).

[C++14: 3.2/6]: There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements [..]

Multiple inclusions of <vector> within the same translation unit are expressly permitted and effectively elided, more than likely by "#ifndef" header guards.

like image 196
Lightness Races in Orbit Avatar answered Sep 21 '22 23:09

Lightness Races in Orbit


The standard has a special exception for templates that allows for duplication of functions that otherwise would violate ODR (such as functions with external linkage and non-inline member functions). from C++11 3.2/5:

If D is a template and is defined in more than one translation unit, then the preceding requirements shall apply both to names from the template’s enclosing scope used in the template definition (14.6.3), and also to dependent names at the point of instantiation (14.6.2). If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.

like image 24
Michael Burr Avatar answered Sep 20 '22 23:09

Michael Burr