Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is there no std::string constructor for reference to array?
    primarykey
    data
    text
    <p>String literals are array objects:</p> <pre class="lang-c prettyprint-override"><code>typeid("hello").name() // char [6] </code></pre> <p>This seems convenient because the size of the string literal (=array) is known at compile time. So why is there no constructor to <code>std::string</code> that takes a reference to an array?</p> <pre class="lang-c prettyprint-override"><code>// this would be great template &lt;int N&gt; std::string(const char (&amp; array)[N]); </code></pre> <p>Instead there are constructors that take <code>const char * s</code>, <code>const char * s, size_t n</code> or two <code>InputIterator</code>s (eg. <code>const char * begin, const char * end</code>). All of these have drawbacks; the array is implicitly converted to a pointer and the size information is lost, so various methods are used to get it back. Working, but increasingly crazy examples:</p> <pre class="lang-c prettyprint-override"><code>// std::string(const char * s) version: std::string s1("hello"); // calls std::strlen(s) internally // std::string(const char * s, size_t n) version: std::string s2("hello", 5); // programmer does std::strlen(s) mentally std::string s3("hello", sizeof("hello")); // have to repeat string literal // macro helper to avoid repeating string literal (ugly and dangerous) #define STRLIT(x) std::string(x, sizeof(x)); // could be a function I guess std::string s4 = STRLIT("hello"); // not much improvement (and macros are evil) // std::string(InputIterator begin, InputIterator end) version: char tmp[] = "hello"; // copy array std::string s5(&amp;tmp[0], &amp;tmp[sizeof(tmp)]); // so you can reference it twice // or trust the compiler to return the same address for both literals std::string s6(&amp;"hello"[0], &amp;"hello"[sizeof("hello")]); // totally crazy </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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