gpt4 book ai didi

c++ - 为什么 std::vector 中的字符串最终具有相同的数据地址?

转载 作者:行者123 更新时间:2023-12-01 22:13:08 26 4
gpt4 key购买 nike

考虑以下 C++ 程序:

#include <iostream>
#include <string>
#include <vector>


int main()
{
std::vector<std::string> v(2, std::string(24,0));
for (auto& s : v) {
std::cout << "Address: " << (void*)s.data() << std::endl;
}
}

Demo

我希望 vector 中的每个字符串都指向不同的内存区域,但是在使用 -D_GLIBCXX_USE_CXX11_ABI=0 编译时,使用 gcc 6.3.0 和 8.2.1,它们显示相同的地址。 (在没有标志的情况下编译时,它们显示不同的地址)。这是为什么?

最佳答案

-D_GLIBCXX_USE_CXX11_ABI=0 (1)std::string 使用 C++11 之前允许的 COW 策略。

Copy On Write 是一种优化策略。使用 COW,当使用相同的值构造多个 std::strings 对象时,只会创建一个底层字符串数组,并且所有对象都将指向它。这就是您在代码中观察到的情况。当写入其中一个对象时,将创建该 std::string 对象唯一的字符串数组的拷贝,然后对其进行修改。

自 C++11 起,此策略是非法的(2),现在大多数实现都使用 SSO(短字符串优化)优化 std::string

<小时/>

(1) Understanding GCC 5's _GLIBCXX_USE_CXX11_ABI or the new ABI

(2) Legality of COW std::string implementation in C++11

关于c++ - 为什么 std::vector<std::string> 中的字符串最终具有相同的数据地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57713636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com