为什么std :: vector <std :: string>中的字符串以相同的数据地址结尾?

太阳垫:

考虑以下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;
    }
}

演示版

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

鲍洛夫:

-D_GLIBCXX_USE_CXX11_ABI=0 (1)与此std::string将其允许预C ++ 11的用途COW策略。

C opy O n W rite是一种优化策略。使用COW,当std::strings使用相同的值构造多个对象,只会创建一个基础字符串数组,并且所有对象都将指向该字符串数组。这就是您在代码中观察到的。当写入一个std::string对象时,将创建对象唯一的字符串数组的副本,然后对其进行修改。

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


(1)了解GCC 5的_GLIBCXX_USE_CXX11_ABI或新的ABI

(2)C ++ 11中COW std :: string实现的合法性

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么不能在C ++中为std :: vector的字符串文字初始值设定项列表创建std :: vector <std :: string>?

为什么std :: string不是std :: vector的特化?

为什么用“ std :: vector <std :: string>&”代替“ void”?

为什么std :: vector <char>比std :: string快?

为什么转置这个 std::vector<std::vector<std::string> > 这么慢?

删除std :: vector <std :: string>中的元素

从 Go 中迭代 `std::vector<std::string>`?

计算std :: string的已分配内存(以及std :: vector中字符串的使用)

使用std :: find检查std :: vector <std :: vector <std :: string >>中的项目

为什么我们有std :: string :: npos但没有std :: vector :: npos?

为什么在比较相同文本的子字符串时std:string不返回0?

为什么在std :: vector擦除中需要begin()?

C ++中的std :: vector与[]比较慢-为什么?

将std :: vector <std :: vector <std :: string >>转换为std :: vector <std :: vector <double >>

std :: vector中的字符串验证

将std :: string索引转换为std :: vector中的整数

什么是 std::vector<std::string> vec{3}; 其实呢?

如何检查std :: vector <std :: string>的元素是否以某些子字符串开头?

C ++使用固定数量的空字符串实例化std :: vector <std :: string>

示例代码中的范围问题,使用分隔符将字符串的std :: string拆分为std :: vector

std::string 不是 std::vector<char> 吗?

如何从std :: vector <char>构造std :: string?

初始化std :: string的std :: vector

使用 std::views 将 std::vector<string> 转换为 C++20 中的 std::string

为什么使用std :: string和std :: string&类似的函数初始化字符串?

std :: vector <string>奇怪的行为

VisualC ++:String ^和std :: vector

为什么返回vector <string>会抛出std :: bad_alloc异常?

为什么可以将 std::string& 分配给 c++ 中的 std::string 变量?