加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用&front()修改std :: string中的基础字符数组

发布时间:2020-12-16 10:00:44 所属栏目:百科 来源:网络整理
导读:参见英文答案 Why is modifying a string through a retrieved pointer to its data not allowed?????????????????????????????????????1个 我必须在我的一个程序中与C库接口,我正在编写一个瘦包装器来使用诸如std :: string之类的C类型.有许多函数接受char
参见英文答案 > Why is modifying a string through a retrieved pointer to its data not allowed?????????????????????????????????????1个
我必须在我的一个程序中与C库接口,我正在编写一个瘦包装器来使用诸如std :: string之类的C类型.有许多函数接受char *和最大长度作为参数,并用零终止的C字符串覆盖char *指向的内存.传统上,我使用堆栈数组并手动将数据复制到字符串中.

std::string call_C_function(int x) {
    char buf[MAX_LEN] = {0}; // MAX_LEN is defined by the library
    size_t len = MAX_LEN;
    C_function(x,buf,&len);
    return std::string(buf,len);
}

我试图避免副本并提出解决方案,但我不知道这是否严格合法:

std::string call_C_function(int x) {
    std::string buf(MAX_LEN,''); // MAX_LEN is defined by the library
    size_t len = MAX_LEN;
    C_function(x,&buf.front(),&len);
    buf.resize(len);
    return buf;
}

这编译和工作,但我有疑问,因为std :: string类使得很难得到一个非const指针指向字符数据. c_str()和data()都返回const指针.该标准明确禁止对这些函数修改缓冲区:

21.4.7.1: The program shall not alter any of the values stored in the character array.

从文档中看,这似乎是合法的,因为front()返回对缓冲区的第一个字符的引用,该字符必须是连续的(我使用的是C 11/14).在21.4.5中,front()的语义是根据operator [](0)定义的,它不禁止修改.

从语言标准的角度来看,这种方法有什么问题吗?似乎这将是一个循环漏洞,允许在21.4.7.1中明确禁止修改.

解决方法

据我读到的C 11:

const charT& front() const;

charT& front();

Requires: !empty()

Effects: Equivalent to operator[](0).

我们来看看operator []:

const_reference operator[](size_type pos) const;

reference operator[](size_type pos);

1 Requires: pos <= size().

2 Returns: *(begin() + pos) if pos < size(),otherwise a reference to
an object of type T with valuecharT(); the referenced value shall not be modified.

由于您预先分配了缓冲区,因此pos将小于size(). begin()返回一个迭代器,因此所有常用的迭代器特性都适用.

因此,根据我对C 11的解释,这种方法应该是合法的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读