Code::Blocks Forums

Developer forums (C::B DEVELOPMENT STRICTLY!) => Development => CodeCompletion redesign => Topic started by: ollydbg on June 14, 2014, 04:43:38 pm

Title: c_str() VS wx_str() for wxString Format output
Post by: ollydbg 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 (http://docs.wxwidgets.org/trunk/classwx_string.html#a667b135c20008042653f82b739f6c3ab)
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() (http://forums.codeblocks.org/index.php/topic,11300.msg76992.html#msg76992), we later remove the #if wxCHECK_VERSION(2, 9, 0) clause, and all is wx_str() now.