I have a constructor for my Arduino-code which is something like the following:
class X {
private:
char* _name;
public:
X(char*);
}
X::X(char* name) {
_name = name;
}
My question is: do I need to allocate a char buffer instead of just relying on the string pointer that was passed? I am not operating on the string (other than to shorten it). I don’t seem to be running into any issues yet, but I wanted to verify.
This is specific to arduino, but responses on C and C++ would be welcomed as well.
It depends.
Basically, with the way the code is now, you are requiring that name have a lifetime greater than the lifetime of the instance of the class. If name is always a string literal, i.e., X(“foo”), then this is acceptable. Otherwise, the caller would have to allocate the string, which is an odd and error prone contract to require.
I would suggest duplicating the string always in the constructor, unless it is clear that it is always expected to be string literal.