你会建议这种方法来复制字符串吗?

Poo*_*ria 0 c++ string performance copy reference

为了获得更高的性能,你是否建议在复制字符串时使用下面的方法,特别是当字符串中有很多字符时,大于12?

 unsigned char one[12]={1,2,3,4,5,6,7,8,9,10,11,12};
 unsigned char two[12];
 unsigned int (& three)[3]=reinterpret_cast<unsigned int (&)[3]>(one);
 unsigned int (& four)[3]=reinterpret_cast<unsigned int (&)[3]>(two);
 for (unsigned int i=0;i<3;i++)
  four[i]=three[i];
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 5

不,(几乎)永远不会.使用std::strcpy(虽然不是在这种情况下,因为你的"字符串"不是零终止)std::copy,或者是std::string复制构造函数.

这些方法经过优化,可以为您完成工作.如果您的代码(或类似的东西)碰巧比通过字符复制的天真字符更快,请放心,strcpy它会在下面使用它.事实上,这就是发生的事情(取决于架构).

不要试图超越现代编译器和框架,除非你是域专家(通常不是那时).