Search code examples
c++stringstring-concatenation

A concatenation between a literal symbol and a string variable then return const char*


I want to concatenate a literal symbol "~" with a string variable.

string dbFile = "data.db";
const char *temporaryFileName = ("~" + dbFile).c_str();  // it must be ~data.db
cout << temporaryFileName << endl;

No errors, but when printing, nothing comes out, why?


Solution

  • Take a look at the return type of the operator that you use:

    string operator+(const char* lhs, string& rhs); // untempletized for simplicity
    

    Note in particular that it returns a new object. As such, the expression ("~" + dbFile) returns a new temporary object. Temporary objects exist only until the full expression statement (unless bound by a reference). In this case, the statement ends at the semicolon on that same line.

    Using the pointer returned by c_str() is allowed only as long as the pointed string object still exists. You use the pointer on the next line where the string no longer exists. The behaviour is undefined.

    A solution: Either modify the original string, or create a new string object. Make sure that the string object exists at least as long as the character pointer is used. Example:

    string dbFile = "data.db";
    auto temporaryFileName = "~" + dbFile;
    cout << temporaryFileName.c_str() << endl;