6/4 Is this valid C++ code?
std::string getStr(void) {
std::string str("foo");
return str;
}
void foo(char *s);
void bar(void) {
foo(getStr().c_str()); // valid?
}
Will foo() receive a valid pointer? Is there any dangling reference or
memory leak? Thanks. --- old timer
\_ Yes, this is fine (except for the const problem noted below).
The temporary std::string object returned by getStr is destroyed
at the end of the statement in which you called getStr.
\_ It can be a pointer to inside the implementation--it doesn't have
to alloc anything.
\_ c_str() returns a const char*, not a char*. foo needs to take a
const char*, and does not need to deallocate anything (nor is it
allowed to modify the contents of the char*). You can cast away the
const for legacy functions that don't deal with const well as long
as you know the function won't try to change the string.
\_ So after I change foo() to "void foo(const char *s);", everything
is good, right? Thanks. -- OP
\_ Yep. -pp
\_ for bonus points think about how many times the copy ctor
is used.
\_ One? -- OP |