I'm creating a class that has a constructor intialized from const char* which should safely construct an object using data provided in the buffer which should contain a string. My worries are, that the user can use this constructor with wrong data, e.g. NULL pointer or pointer to not-allocated memory or something like that. The point is, in that case I want to finish creating object (which will be in undefined, but correct state), without causing segfault if, for example, user sent me a pointer to data I shouldn't read. I thought of sending all input validation to std::string constructor, so the constructor would look like this:
Foo(const char *s) : Foo(std::string(s)) {}
But my teacher called this a "wrong idea". So, what is the proper way to deal with this situation then?
One more thing, I can't use exceptions in that case (this is part of my homework assignment in course which hasn't taught it yet).
The problem is that there are some things you absolutely cannot check for. The biggest of the group is a pointer to invalid memory. For example :
char* blarg = new char[50];
delete blarg;
Foo(blarg);
Here is another conversation about what you're asking. Some good answers are there but they basically say the same thing. When dealing with a pointer input there is no way to be 100% sure the user didn't do something stupid like calling delete on the pointer before passing it in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With