Can we rely on the reduce-capacity trick?

后端 未结 4 715
广开言路
广开言路 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:44

    How this works is probably entirely implementation-defined. Unlike containers such as vector, strings can have very different implementations.

    If the string implementation uses small string optimization, then you can't lower capacity beyond a certain threshold. If the string implementation uses copy-on-write, then no write occurs and no real copy is made.

    According to http://www.gotw.ca/gotw/054.htm, shrink-to-fit and clear-completely are different tricks. If the intention is to clear completely, then swapping with a default-constructed string can be expected to give better results.

提交回复
热议问题