使用STL会显着增加占地面积吗?

13 c++ stl

使用STL会显着增加占地面积吗?你们可以分享一下你对此事的经历吗?构建小型库的最佳实践是什么?

cta*_*cke 20

没有一个答案,因为STL是一组模板.模板本质上只在使用时编译.因此,您可以包含所有STL,如果没有实际使用,则STL添加的占用空间将为零.如果你有一个非常小的应用程序设法使用许多具有不同专业的不同模板,则占用空间可能很大.


Mar*_*ork 11

关于STL的事情,因为它是所有模板,它只会在实际使用时增加大小.如果您不使用方法,则不会实例化该方法.

但是你使用的东西总会有成本.

但你必须要问的真正的问题.尺寸是否比你自己的实施更大或更小?如果您不使用STL,您使用什么?你可以自己动手写,但这有自己的成本.它不是零空间,它不会经过充分测试,您将不会遵循既定的最佳实践.

所以实际上没有它不会膨胀你的代码.
因为通过某些其他方法添加等效功能将添加尽可能多的代码,它将不会经过充分测试.

其他帖子指出模板代码必须是内联的或具有多个定义.
这绝对是错的.

这些方法标记为内联.但是,如果该方法实际上是内联的,则由编译器决定.编译器内联非常复杂,只有在内联才能实现,这有助于优化策略的使用.

如果没有内联,那么将在使用该方法的每个编译单元中生成该方法的副本.但是,对于C++链接器的要求是,当应用程序链接到可执行文件时,它必须删除这些方法的所有副本.如果编译器没有删除额外的副本,则必须生成多定义链接器错误.

这很容易显示:
以下说明:

  • 方法_M_insert_aux()不是内联的.
  • 它放在两个编译单元中.
  • 只有该方法的一个副本位于最终的可执行文件中.

a.cpp

#include <vector>

void a(std::vector<int>& l)
{
    l.push_back(1);
    l.at(0) = 2;
}
Run Code Online (Sandbox Code Playgroud)

b.cpp

#include <vector>

void b(std::vector<int>& l)
{
    l.push_back(1);
    l.at(0) = 2;
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include <vector>

void a(std::vector<int>&);
void b(std::vector<int>&);

int main()
{
    std::vector<int>    x;
    a(x);
    b(x);
}
Run Code Online (Sandbox Code Playgroud)

检查

>g++ -c a.cpp
>g++ -c b.cpp

>nm a.o
<removed other stuff>
000000a0 S __ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi
<removed other stuff>

>nm b.o
<removed other stuff>
000000a0 S __ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi
<removed other stuff>

>c++filt __ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi
std::vector<int, std::allocator<int> >::_M_insert_aux(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, int const&)

>g++ a.o b.o main.cpp
nm a.out | grep __ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi
00001700 T __ZNSt6vectorIiSaIiEE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPiS1_EERKi
Run Code Online (Sandbox Code Playgroud)