Here is the code which I got:
struct ChoiceLine
{
const char *prompt;
ChoiceLine(const char *pr):
prompt(pr) //can this cause a memory leak?
{
;
}
};
...
ChoiceLine choiceLine("hello world");
So is it OK to initialize a const char*
with another const char*
?
PS: I know about std::string
, which unfortunately does not fit my purposes.
Yes that's fine if a little unsafe: the memory associated with prompt
is not owned by the class instance.
(In your particular case ChoiceLine choiceLine("hello world");
all will be well since the string literal will last the life of the program).
Hence it would have to be kept in scope for as long as the class instance was in scope.
If I were you I'd use a std::string
as your class member and suffer a deep copy.
There is no dynamic memory allocation, so there is no memory leak. Your data member just points to a string literal. It is the equivalent of doing this:
const char* c = "Hello, World!";
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