c++ - Visual Studio 下的 string::swap 复杂度

标签 c++ visual-studio-2010 stl

cppreference页面说 std::basic_string::swap 它具有恒定的复杂性。正如我所假设的那样,这意味着复制内容不会发生,只会发生指针交换或类似的情况。我写了一个测试代码并体验到它确实在VS2010下移动了内容。测试代码:

std::string s1("almafa");
std::string s2("kortefa");
std::cout << "s1.c_str(): "<< (void*)s1.c_str() << std::endl;
std::cout << "s2.c_str(): "<< (void*)s2.c_str() << std::endl;
std::cout << "SWAP!" << std::endl;
s1.swap(s2);
std::cout << "s1.c_str(): "<< (void*)s1.c_str() << std::endl;
std::cout << "s2.c_str(): "<< (void*)s2.c_str() << std::endl;

g++ 4.6.3 上的输出

s1.c_str(): 0x22fe028
s2.c_str(): 0x22fe058
SWAP!
s1.c_str(): 0x22fe058
s2.c_str(): 0x22fe028

VS2010 上的输出

s1.c_str(): 000000000022E2D0
s2.c_str(): 000000000022E320
SWAP!
s1.c_str(): 000000000022E2D0
s2.c_str(): 000000000022E320

这是与标准的差异还是发生了我不知道的事情?

最佳答案

std::string 的某些实现使用短字符串优化:

来自 How is std::string implemented? :

a "short string optimization" (SSO) implementation. In this variant, the object contains the usual pointer to data, length, size of the dynamically allocated buffer, etc. But if the string is short enough, it will use that area to hold the string instead of dynamically allocating a buffer.

所以在你的情况下交换做一个拷贝但大小固定,所以 O(1)。

关于c++ - Visual Studio 下的 string::swap 复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25201758/

相关文章:

c++ - 静态变量初始化代码永远不会被调用

c++ - 如何使用 __stdcall 来限定 C++ lambda?

visual-studio-2010 - 在哪里可以找到 Microsoft Visual Studio 2010 卸载实用程序?

c++ - 将 unique_ptr 从一个集合移动到另一个集合

c++ - 如何访问第二个 map 迭代器?

c++ - 如何使用消息正确创建自定义异常?

c++ - 在 C++ 中比较 & 与 % 的速度

c++ - 清除谷歌测试错误中的标准输出错误

c# - 将文件从 C# Windows 窗体中的文件夹填充到列表框中

c++ - 如何为已明确定义其比较函数的集合定义迭代器?