Xeo*_*Xeo 10 c++ string language-lawyer c++11
§21.4.5 [string.access]
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
Run Code Online (Sandbox Code Playgroud)
返回:
*(begin() + pos)ifpos < size().否则,返回对charT具有value 的类型对象的引用charT(),其中修改对象会导致未定义的行为.
对我来说,第二部分意味着这个"类型对象charT"可能存在于存储在std::string对象中的序列之外.符合性的示例实现operator[]:
reference operator[](size_type pos){
static contexpr charT default = charT();
if(pos == size())
return default;
return buf[pos];
}
Run Code Online (Sandbox Code Playgroud)
现在,c_str()/ data(),按以下方式指定operator[]:
§21.4.7 [string.accessors]
const charT* c_str() const noexcept;
const charT* data() const noexcept;
Run Code Online (Sandbox Code Playgroud)
返回:一个指针
p,p + i == &operator[](i)用于每个iin[0,size()].
这将使上述operator[]实现不符合,如p + size() != &operator[](size()).但是,通过一些技巧,你可以避免这个问题:
reference operator[](size_type pos){
static contexpr charT default = charT();
if(pos == size() && !evil_context) // assume 'volatile bool evil_context;'
return default;
return buf[pos];
}
struct evil_context_guard{
volatile bool& ctx;
evil_context_guard(volatile bool& b)
: ctx(b) {}
~evil_context_guard(){ b = false; }
};
const charT* c_str() const noexcept{
evil_context_guard g(evil_context = true);
// now, during the call to 'c_str()', the requirement above holds
// 'p + i == &operator[](i) for each i in [0,size()]'
const charT* p = &buf[0];
assert(p+size() == &operator[](size()));
return p;
}
Run Code Online (Sandbox Code Playgroud)
现在,显而易见的问题是......
以上代码是否真的符合或者我忽略了什么?
忽略给定的代码,仅考虑问题,我认为
因此,它看起来是一个缺陷。
检查已知库缺陷列表,显然尚未报告此问题。
因此,正如我在聊天中所说,我建议将其发布到 [comp.std.c++],以便解决它是否确实是缺陷的问题,如果是,则将其放入缺陷列表并修复。