Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>By taking a C string the C++03 <a href="http://en.cppreference.com/w/cpp/io/basic_fstream" rel="noreferrer"><code>std::fstream</code></a> class reduced dependency on the <code>std::string</code> class. In C++11, however, the <code>std::fstream</code> class does allow passing a <code>std::string</code> for its constructor parameter.</p> <p>Now, you may wonder why isn't there a transparent conversion from a <code>std:string</code> to a C string, so a class that expects a C string could still take a <code>std::string</code> just like a class that expects a <code>std::string</code> can take a C string.</p> <p>The reason is that this would cause a conversion cycle, which in turn may lead to problems. For example, suppose <code>std::string</code> would be convertible to a C string so that you could use <code>std::string</code>s with <code>fstream</code>s. Suppose also that C string are convertible to <code>std::string</code>s as is the state in the current standard. Now, consider the following:</p> <pre><code>void f(std::string str1, std::string str2); void f(char* cstr1, char* cstr2); void g() { char* cstr = "abc"; std::string str = "def"; f(cstr, str); // ERROR: ambiguous } </code></pre> <p>Because you can convert either way between a <code>std::string</code> and a C string the call to <code>f()</code> could resolve to either of the two <code>f()</code> alternatives, and is thus ambiguous. The solution is to break the conversion cycle by making one conversion direction explicit, which is what the STL chose to do with <code>c_str()</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload