DEV Community

Discussion on: Is there a way to convert dynamically allocated memory to static memory OR copy ptr contents in C/C++?

Collapse
 
pgradot profile image
Pierre Gradot

There is so much to say about this code... Some remarks:

1- Why mixing char* and unsigned char*?
2- Why usig unsigned char? oO
3- this-> is not needed, most of the time
4- I see getlen(std::string) --> why don't you simply use std::string? Is this code only for educational purpose?
5- getlen(unsigned char const*) : aren't you missing ++i in the for loop?
5- TOO MUCH CASTS /!\
6- Don't use C style casts. Use C++ cast operators
7- unsigned char const* const str = nullptr; --> why is this pointer const?! You want to set it in the constructor Oo

Thread Thread
 
baenencalin profile image
Calin Baenen

Note: What's with the two random "Oo"s?

1- Because I prefer unsigned char when working with characters, and unsigned char is compatible with char, but I don't know if it's compatible with signed char. Though, I guess I should just use char, huh?
2- For the reason stated above (I love unsigned characters).
3- I know, but since I work in the context of Java, and JavaScript, I prefer the this., because I've gotten attached to using it for properties.
4- I just wanted to make my own String type for fun, to add my own custom methods, without having to dig into the internals of the tradition std::string. - So, technically, I guess you could say so.
5- Yes. But it should be an i++ and not ++i. (Since won't the latter increment i before the loop begins?)
6- This was a deliberate decision. I realize they can cause errors, and allow too much freedom. - But, this decision is also in part to not understanding how C++'s typecasts work, and why they wouldn't just replace C's typecasts (if they were so bad). (I know, compatibility reasons, blah blah blah, but they still could have made it work, adding their own casts with (Type) value.)
7- I do. And I still can in the member-initializer-list, since those apparently happen before the instantiation of the class (or right as it happens).

Thread Thread
 
pgradot profile image
Pierre Gradot

NOTE: this is juste a smiley: Oo => en.wikipedia.org/wiki/List_of_emot... => Surprised

1/2- Not everything is a matter a preference. See stackoverflow.com/questions/75191/...
3- Usually, we don't add this-> when its not needed. It improves codes' readability.*
4- OK
5- Both occur at the end of each iteration. In C++, we generally use ++i in for loops. See betterprogramming.pub/stop-using-i...
6- If you don't understand the C++ cast operators, then you don't understand what you code do. You should really use them. See stackoverflow.com/a/1609185/12342718
7- My bad: it works in the initialization list. Note that you have a cast that takes away the const.