ArduinoCore-API icon indicating copy to clipboard operation
ArduinoCore-API copied to clipboard

class String constant opeator [] should return const reference!

Open LiangZuoting opened this issue 12 years ago • 5 comments

commonly people want get the buffer ptr by a constant String object like below: const String &str; const char *p = &str[0];

BUT now the constant operator [] returns a temp char object, i don't think it is better.

LiangZuoting avatar May 13 '13 04:05 LiangZuoting

You have created a pointer to a char obkect and then tryed to access to its content, but the objects doesn't exist. Yiu are reading garbage. Ask in the forum for this kind of problem Il giorno 13/mag/2013 06:15, "Liang zuoting" [email protected] ha scritto:

commonly i want get the buffer ptr by a constant String object like below: const String &str; const char *p = &str[0];

BUT now the constant operator [] returns a temp char object, i don't think it is better.

— Reply to this email directly or view it on GitHubhttps://github.com/arduino/Arduino/issues/1413 .

lestofante avatar May 13 '13 06:05 lestofante

ye i know what i was doing. what i mean, look at the c++ stl string or other string implement, almost of them return a const reference but a temp object ! in my opinion it is UNREASONABLE !

LiangZuoting avatar May 14 '13 01:05 LiangZuoting

Like it not, the String class API supports writing to the string with array syntax. It's had this feature since the first release in Arduino 0019, so there's probably no way the Arduino Team will remove that feature now.

String supports this syntax:

String str = "test"; str[2] = 'x'; // "test" -> "text"

When the user writes this:

str[10] = 'x';

what do you believe String should do?

Going back in time to before Arduino 0019 to remove writable array syntax is probably not an option.

PaulStoffregen avatar Jun 20 '13 20:06 PaulStoffregen

I think I'm with @qinqingege on this one. This is not about removing the [] functionality as @PaulStoffregen says but about making it more array-like. Why can you do

const char *x = "hello";
const char *p = &x[1];

but not

String str = "hello";
const String &x = str;
const char *p = &x[1];

?

This would be solved by just replacing the current char String::operator[]( unsigned int index ) const with const char &String::operator[]( unsigned int index ) const. I think this would be more elegant as it would be consistent with the non-const version (which would remain as it is now: char &String::operator[]( unsigned int index )).

cousteaulecommandant avatar Dec 25 '17 23:12 cousteaulecommandant

@cousteaulecommandant thanks for summarizing the needed change. It looks like a good and consistent change to me.

matthijskooijman avatar Dec 26 '17 11:12 matthijskooijman