2 ms·
That still would not solve the issue as you'd manually be updating length when you modified your string. This is why instead of rolling your own lib, it's proba
by goldenkey 13y ago
That still would not solve the issue as you'd manually be updating length when you modified your string. This is why instead of rolling your own lib, it's probably better to use the existing dynamically allocated C string libs out there to take care of it. Right, all the libs use a struct, as there are no first-class objects in C.
- mbel 13y agoActually I would prefer to write the length at creation time and don't mutate the string at all (and yes I'm aware that the line of code above is quite far from ensuring immutability); afaik most of those "OOP languages" use immutable strings. But yes, you are absolutely right in most cases using existing libraries is superior solution to any own, rolled-out-just-a-second-ago implementation of string; I used it only to demonstrate that storing length with a buffer address is hardly a OOP technique.
- goldenkey 13y agoHere's how you'd do that mbel: const char[] str = "This is a string"; int len = sizeof(str) / sizeof(str[0]); Compile-time..still not dynamic immutability though. The array pointer can't change, the buffer size can't change, and the char components are const. Immutable but then again, you can violate that quite easily. And it's only compile-time immutability, which isn't all that great.