Lets say I declare two STL list<T> in main:
list<Animal> a;
list<Person> p;
how many copies of the STL list functions will be in your object code?
My educated guess is two since both are instantiated at compile time..
Can anyone verify this ?
Lets say I declare two STL list<T> in main:
list<Animal> a;
list<Person> p;
how many copies of the STL list functions will be in your object code?
My educated guess is two since both are instantiated at compile time..
Can anyone verify this ?
That depends on the quality of your implementation.
A particularly bad compiler might instantiate everything.
A particularly good compiler might realise that nothing is actually used and remove everything.
Eg
nm is the Unix tool to tell you what symbol names exist in an object file.Code:$ cat bar.cpp #include <iostream> #include<cstdlib> #include <list> #include <ctime> using namespace std; struct Animal { }; struct Person { }; int main ( ) { list<Animal> a; list<Person> p; } g++ bar.cpp nm -C a.out g++ -O2 bar.cpp nm -C a.out
Specifying -O2 gets a different answer.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Only functions that are used will be instantiated. In this case, just the constructor and destructor for both objects, four functions total. As Salem points out, even those may not be generated if the variables can be proven to be unused and be removed.
However, I disagree that looking at the symbol names is a good test, because if the functions are inlined, they will still generate code, but they won't appear in the symbol table.
Last edited by King Mir; 06-30-2013 at 10:02 AM.
It is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.
Note that the STL is actual code (as opposed to headers) that is included with your code. This is how the templates can handle type specific objects with what is otherwise generic code.
What I meant was that STL is C++ template source code, instead of prototypes to functions in a library. So if you use a template function from the STL, the code for that template function is getting complied along with your code. I'm not sure how the compiler handles the case where a template function is used multiple times with multiple types, in terms in how many instances of that function (but with different types) your program will end up with.