返回类型时c_str()vs.data() [英] c_str() vs. data() when it comes to return type

查看:108
本文介绍了返回类型时c_str()vs.data()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11之后,我想到了c_str()data() 等同地.

After C++11, I thought of c_str() and data() equivalently.

C ++ 17为后者引入了一个重载,该重载返回了一个非恒定指针(

C++17 introduces an overload for the latter, that returns a non-constant pointer (reference, which I am not sure if it's updated completely w.r.t. C++17):

const CharT* data() const;    (1)   
CharT* data();                (2)   (since C++17)

c_str() 只会返回常量指针:

const CharT* c_str() const;

为什么在C ++ 17中区分这两种方法,尤其是当C ++ 11是使它们同质的一种时?换句话说,为什么只有一种方法有重载,而另一种却没有?

Why the differentiation of these two methods in C++17, especially when C++11 was the one that made them homogeneous? In other words, why only the one method got an overload, while the other didn't?

推荐答案

The new overload was added by P0272R1 for C++17. Neither the paper itself nor the links therein discuss why only data was given new overloads but c_str was not. We can only speculate at this point (unless people involved in the discussion chime in), but I'd like to offer the following points for consideration:

  • 即使只是将重载添加到data,也会破坏一些代码;保持这种变化保守是减少负面影响的一种方法.

  • Even just adding the overload to data broke some code; keeping this change conservative was a way to minimize negative impact.

到目前为止,c_str函数与data完全相同,并且实际上是一种用于接口"采用"C字符串"即不可变的代码的旧版"功能,以null终止的char数组.由于您始终可以将c_str替换为data,因此没有特别的理由要添加到该旧界面.

The c_str function had so far been entirely identical to data and is effectively a "legacy" facility for interfacing code that takes "C string", i.e. an immutable, null-terminated char array. Since you can always replace c_str by data, there's no particular reason to add to this legacy interface.

我意识到P0292R1的真正动机是确实存在遗留的API,这些API错误地或出于C的原因即使不发生突变也仅采用可变的指针.都一样,我想我们不想在绝对必要的字符串本已庞大的API中添加更多内容.

I realize that the very motivation for P0292R1 was that there do exist legacy APIs that erroneously or for C reasons take only mutable pointers even though they don't mutate. All the same, I suppose we don't want to add more to string's already massive API that absolutely necessary.

还有一点:从C ++ 17开始,您现在

One more point: as of C++17 you are now allowed to write to the null terminator, as long as you write the value zero. (Previously, it used to be UB to write anything to the null terminator.) A mutable c_str would create yet another entry point into this particular subtlety, and the fewer subtleties we have, the better.

这篇关于返回类型时c_str()vs.data()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆