Can we rely on the reduce-capacity trick?

后端 未结 4 713
广开言路
广开言路 2020-11-28 16:07

Is it actually guaranteed anywhere that the following reduce-capacity trick will \"work\"?

int main() {
   std::string s = \"lololololol\";
   s = \"\";              


        
4条回答
  •  抹茶落季
    2020-11-28 16:23

    On his errata page for "Effective STL," Scott Meyers notes:

    When string implementations use reference counting, the swap trick using the copy constructor doesn't decrease the capacity, because the copy constructor isn't allocating any memory; it's just adjusting a reference count. A more reliable way to perform shrink-to-fit is to create the temporary string via the range constructor, e.g., string(s.begin(), s.end()).swap(s); This version of the swap trick is safer for vectors, too, because it eliminates any chance that the copy constructor will copy the other vector's excess capacity (which implementations are permitted to do).

    As for the 'guarantee,' Meyers notes:

    The language police require that I inform you that there's no guarantee that this technique will truly eliminate excess capacity. Implementers are free to give vectors and strings excess capacity if they want to, and sometimes they want to. [Effective STL, Item 17]

提交回复
热议问题