Author Topic: c_str() VS wx_str() for wxString Format output  (Read 9564 times)

Offline ollydbg

  • Developer
  • Lives here!
  • *****
  • Posts: 5910
  • OpenCV and Robotics
    • Chinese OpenCV forum moderator
c_str() VS wx_str() for wxString Format output
« on: June 14, 2014, 04:43:38 pm »
I see many code in our code base

Code
Function("xxxx %s", songwxString.wx_str());

Also, some use c_str().

What is the preferred way.

I look at the document, in wx2.8.12
Quote
wxString::c_str
const wxChar * c_str() const

Returns a pointer to the string data (const char* in ANSI build, const wchar_t* in Unicode build).

Note that the returned value will not be convertible to char* or wchar_t* in wxWidgets 3, consider using char_str or wchar_string if you need to pass string value to a function expecting non-const pointer.


No official document in 2.8.12, but I see such code in the header file
Code
    // identical to c_str(), for wxWin 1.6x compatibility
    const wxChar* wx_str()  const { return c_str(); }

Note, c_str just return a pointer point to the internal buffer.
Code
  const wxChar* c_str() const { return m_pchData; }
  const wxChar* data() const { return m_pchData; }
So, they are the same.


Now, in wx 3.0 (trunk), I see: wx_str
Quote
const wxStringCharType* wxString::wx_str    (       )    const

Explicit conversion to C string in the internal representation (either wchar_t* or UTF-8-encoded char*, depending on the build).

But c_str are some different
Quote
wxCStrData wxString::c_str    (       )    const

Returns a lightweight intermediate class which is in turn implicitly convertible to both const char* and to const wchar_t*.

Given this ambiguity it is mostly better to use wc_str(), mb_str() or utf8_str() instead.

Please see the Unicode Support in wxWidgets for more information about it.

Note that the returned value is not convertible to char* or wchar_t*, use char_str() or wchar_str() if you need to pass string value to a function expecting non-const pointer.

See Also
    wc_str(), utf8_str(), c_str(), mb_str(), fn_str()

Not quite understand the document.

Any suggestions?


EDIT
A former discussion about Question about wx_str() and c_str(), we later remove the #if wxCHECK_VERSION(2, 9, 0) clause, and all is wx_str() now.
« Last Edit: June 14, 2014, 04:47:34 pm by ollydbg »
If some piece of memory should be reused, turn them to variables (or const variables).
If some piece of operations should be reused, turn them to functions.
If they happened together, then turn them to classes.