Can `std :: basic_string :: operator []` return a nul terminator remote protected page?

So, operator[] does not directly say that s[s.size()] should be the character after s[s.size()-1] in memory. Seems worded to avoid this requirement.

But s.data() indicates that s.data()+k == &s[k] and s.data() should return a pointer.

Ignoring the seeming standard defect of using & on CharT above rather than std::addressof , is the implementation free to return another CharT (say, one on a secure page or in ROM) for s[s.size()] before the first call to s.data() ? (Obviously, this can cause the buffer to end on a read-only page with zero on it, I'm talking about a different situation)

To be explicit:

As far as I can tell, if s.data() never called (and the compiler can prove it), then s[s.size()] need not be adjacent to the rest of the buffer.

Can std::addressof(s[s.size()]) change after calling s.data() , and the implementation will comply with the standard (as long as s.data()+k == &s[k] has .data() evaluated before [] , but the compiler has the right to ensure its execution). Or are there demands for immutability that I don't see?

+8
c ++ stdstring language-lawyer c ++ 14 c ++ 17
source share
1 answer

Since C ++ 11, std :: string needs to be stored in continuous memory. This is a quote from the C ++ 11 standard (section 24.4.1.4):

char-like objects in the basic_string object should be stored contiguously. That is, for any basic_string object s, the identity & * (s.begin () + n) == & * s.begin () + n holds for all N values ​​such that 0 <= n <s.size () .

This quote about the return value of the [] operator indicates that it returns the same as &*(s.begin()+n) (section 21.4.5.1):

* (begin () + pos) if pos <size (), Otherwise returns a reference to an object of the diagram type with the value diagram (), where changing the object leads to undefined behavior

Then we quote this quote about the return value of data () in (section 24.4.7.1):

A pointer n such that p + i == & operator [] (i) for each i in [0, size ()].

Thus, the data is returned to the same as you, using the & [] operator. And any value between you obtained using the & operator should be kept adjacent. Thus, you can conclude that both return a pointer to continuous memory. Therefore, it will not return a pointer to the page with the distance.

Please note that this only applies to C ++ 11. Such guarantees were not made by the standard until C ++ 11.

+1
source share

All Articles