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/