0

I'm mostly interested in the general case of:

T& tr = SomeSource();
T* tp = &tr;
T t = tp[5];

The specific example that provoked this question (and seems to have been asked befor) is:

std::string s = "01234567";
char *c = &s[0];

// Do something with it.
c[4] = 'f';  // Is this valid or undefined behavior

Context:

  • Writing to std::string::data is explicitly UB.
  • std::string::operator[] can return references that writing to is UB (e.g. out of bounds).
  • The intent of the motivating case is to avoid a C function to populate a char* and end up with that in a C++ std::string without having to copy it.
Community
  • 1
  • 1
BCS
  • 75,627
  • 68
  • 187
  • 294
  • @Praetorian: the question you cited attempt to resolve the specific case I mentioned, but takes as given (and without question) that the answer to the question I asked is "not UB". – BCS Oct 20 '14 at 13:40
  • 2
    your generic case doesn't make any sense. also, there's no information what the operator `[]` does there. – Karoly Horvath Oct 20 '14 at 13:42
  • I think my reply to your comment on the linked dupe should answer your question. I don't understand your *general case* example. What is `t`? And how are the preceding reference and pointer significant? Can you change that example to using `std::string`? If you feel your question is still unanswered, I'll reopen it for you. – Praetorian Oct 20 '14 at 14:35
  • 1
    I think there is a typo, `t[5]` should be `tp[5]`. – Oktalist Oct 20 '14 at 14:43
  • @Oktalist: yes, typo, corrected. – BCS Oct 20 '14 at 19:47

0 Answers0