{"id":13204,"date":"2022-06-16T14:19:23","date_gmt":"2022-06-16T21:19:23","guid":{"rendered":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/?p=13204"},"modified":"2025-01-02T22:17:09","modified_gmt":"2025-01-03T06:17:09","slug":"stdstring_view-part-2","status":"publish","type":"post","link":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/stdstring_view-part-2\/","title":{"rendered":"5.9 &#8212; std::string_view (part 2)"},"content":{"rendered":"<p>In prior lessons, we introduced two string types: <code>std::string<\/code> (<a href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/introduction-to-stdstring\/\">5.7 -- Introduction to std::string<\/a>) and <code>std::string_view<\/code> (<a href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/introduction-to-stdstring_view\/\">5.8 -- Introduction to std::string_view<\/a>).<\/p>\n<p>Because <code>std::string_view<\/code> is our first encounter with a view type, we&#8217;re going to spend some additional time discussing it further.  We will focus on how to use <code>std::string_view<\/code> safely, and provide some examples illustrating how it can be used incorrectly.  We&#8217;ll conclude with some guidelines on when to use <code>std::string<\/code> vs <code>std::string_view<\/code>.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">An introduction to owners and viewers<\/p>\n<p>Let&#8217;s sidebar into an analogy for a moment.  Say you&#8217;ve decided that you&#8217;re going to paint a picture of a bicycle.  But you don&#8217;t have a bicycle!  What are you to do?<\/p>\n<p>Well, you could go to the local cycle shop and buy one.  You would own that bike.  This has some benefits: you now have a bike that you can ride.  You can guarantee the bike will always be available when you want it.  You can decorate it, or move it.  There are also some downsides to this choice.  Bicycles are expensive.  And if you buy one, you are now responsible for it.  You have to periodically maintain it.  And when you eventually decide you don&#8217;t want it any more, you have to properly dispose of it.<\/p>\n<p>Ownership can be expensive.  As an owner, it is your responsibility to acquire, manage, and properly dispose of the objects you own.<\/p>\n<p>On your way out of the house, you glance out your window front.  You notice that your neighbor has parked their bike across from your window.  You could just paint a picture of your neighbor&#8217;s bike (as seen from your window) instead.  There are lots of benefits to this choice.  You save the expense of having to go acquire your own bike.  You don&#8217;t have to maintain it.  Nor are you responsible for disposing of it.  When you are done viewing, you can just shut your curtains and move on with your life.  This ends your view of the object, but the object itself is not affected by this.  There are also some potential downsides to this choice.  You can&#8217;t paint or customize your neighbors bike.  And while you are viewing the bike, your neighbor may decide to change the way the bike looks, or move it out of your view altogether.  You may end up with a view of something unexpected instead.<\/p>\n<p>Viewing is inexpensive.  As a viewer, you have no responsibility for the objects you are viewing, but you also have no control over those objects.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\"><code>std::string<\/code> is a (sole) owner<\/p>\n<p>You might be wondering why <code>std::string<\/code> makes an expensive copy of its initializer.  When an object is instantiated, memory is allocated for that object to store whatever data it needs to use throughout its lifetime.  This memory is reserved for the object, and guaranteed to exist for as long as the object does.  It is a safe space.  <code>std::string<\/code> (and most other objects) copy the initialization value they are given into this memory so that they can have their own independent value to access and manipulate later.  Once the initialization value has been copied, the object is no longer reliant on the initializer in any way.<\/p>\n<p>And that&#8217;s a good thing, because the initializer generally can&#8217;t be trusted after initialization is complete.  If you imagine the initialization process as a function call that initializes the object, who is passing in the initializer?  The caller.  When initialization is done, control returns back to the caller.  At this point, the initialization statement is complete, and one of two things will typically happen:<\/p>\n<ul>\n<li>If the initializer was a temporary value or object, that temporary will be destroyed immediately.\n<\/li>\n<li>If the initializer was a variable, the caller still has access to that object.  The caller can then do whatever it wants with the object, including modify or destroy it.\n<\/li>\n<\/ul>\n<div class=\"cpp-note cpp-lightbluebackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Key insight<\/p>\n<p>An initialized object has no control over what happens to the initialization value after initialization is finished.\n<\/p><\/div>\n<p>Because <code>std::string<\/code> makes its own copy of the initializer, it doesn&#8217;t have to worry about what happens to the initializer after initialization is finished.  The initializer can be destroyed, or modified, and it doesn&#8217;t affect the <code>std::string<\/code>.  The downside is that this independence comes with the cost of making an expensive copy.<\/p>\n<p>In the context of our analogy, <code>std::string<\/code> is an owner -- it is responsible for acquiring its string data from the initializer, managing access to the string data, and properly disposing of the string data when the <code>std::string<\/code> object is destroyed.<\/p>\n<div class=\"cpp-note cpp-lightbluebackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Key insight<\/p>\n<p>In programming, when we call an object an owner, we generally mean that it is the sole owner (unless otherwise specified).  Sole ownership (also called single ownership) ensures it is clear who has responsibility for that data.\n<\/p><\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">We don&#8217;t always need a copy<\/p>\n<p>Let&#8217;s revisit this example from the prior lesson:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n#include &lt;string&gt;\r\n\r\nvoid printString(std::string str) \/\/ str makes a copy of its initializer\r\n{\r\n    std::cout &lt;&lt; str &lt;&lt; '\\n';\r\n}\r\n\r\nint main()\r\n{\r\n    std::string s{ \"Hello, world!\" };\r\n    printString(s);\r\n\r\n    return 0;\r\n}<\/code><\/pre>\n<p>When <code>printString(s)<\/code> is called, <code>str<\/code> makes an expensive copy of <code>s<\/code>.  The function prints the copied string and then destroys it.<\/p>\n<p>Note that <code>s<\/code> is already holding the string we want to print.  Could we just use the string that <code>s<\/code> is holding instead of making a copy?  The answer is possibly -- there are three criteria we need to assess:<\/p>\n<ul>\n<li>Could <code>s<\/code> be destroyed while <code>str<\/code> is still using it?  No, <code>str<\/code> dies at the end of the function, and <code>s<\/code> exists in the scope of the caller and can&#8217;t be destroyed before the function returns.\n<\/li>\n<li>Could <code>s<\/code> be modified while <code>str<\/code> is still using it?  No, <code>str<\/code> dies at the end of the function, and the caller has no opportunity to modify the <code>s<\/code> before the function returns.\n<\/li>\n<li>Does <code>str<\/code> modify the string in some way that the caller would not expect?  No, the function does not modify the string at all.\n<\/li>\n<\/ul>\n<p>Since all three of these criteria are false, there is no risk in using the string that <code>s<\/code> is holding instead of making a copy.  And since string copies are expensive, why pay for one that we don&#8217;t need?<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\"><code>std::string_view<\/code> is a viewer<\/p>\n<p><code>std::string_view<\/code> takes a different approach to initialization.  Instead of making an expensive copy of the initialization string, <code>std::string_view<\/code> creates an inexpensive view <em>of<\/em> the initialization string.  The <code>std::string_view<\/code> can then be used whenever access to the string is required.<\/p>\n<p>In the context of our analogy, <code>std::string_view<\/code> is a viewer.  It views an object that already exists elsewhere, and cannot modify that object.  When the view is destroyed, the object being viewed is not affected.  Having multiple viewers viewing an object simultaneously is fine.<\/p>\n<p>It is important to note that a <code>std::string_view<\/code> remains dependent on the initializer through its lifetime.  If the string being viewed is modified or destroyed while the view is still being used, unexpected or undefined behavior will result.<\/p>\n<p>Whenever we use a view, it is up to us to ensure these possibilities do not occur.<\/p>\n<div class=\"cpp-note cpp-lightredbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Warning<\/p>\n<p>A view is dependent on the object being viewed.  If the object being viewed is modified or destroyed while the view is still being used, unexpected or undefined behavior will result.\n<\/p><\/div>\n<p>A <code>std::string_view<\/code> that is viewing a string that has been destroyed is sometimes called a <strong>dangling<\/strong> view.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\"><code>std::string_view<\/code> is best used as a read-only function parameter<\/p>\n<p>The best use for <code>std::string_view<\/code> is as a read-only function parameter.  This allows us to pass in a C-style string, <code>std::string<\/code>, or <code>std::string_view<\/code> argument without making a copy, as the <code>std::string_view<\/code> will create a view to the argument.<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n#include &lt;string&gt;\r\n#include &lt;string_view&gt;\r\n\r\nvoid printSV(std::string_view str) \/\/ now a std::string_view, creates a view of the argument\r\n{\r\n    std::cout &lt;&lt; str &lt;&lt; '\\n';\r\n}\r\n\r\nint main()\r\n{\r\n    printSV(\"Hello, world!\"); \/\/ call with C-style string literal\r\n\r\n    std::string s2{ \"Hello, world!\" };\r\n    printSV(s2); \/\/ call with std::string\r\n\r\n    std::string_view s3 { s2 };\r\n    printSV(s3); \/\/ call with std::string_view\r\n       \r\n    return 0;\r\n}<\/code><\/pre>\n<p>Because the <code>str<\/code> function parameter is created, initialized, used, and destroyed before control returns to the caller, there is no risk that the string being viewed (the function argument) will be modified or destroyed before our <code>str<\/code> parameter.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Should I prefer <code>std::string_view<\/code> or <code>const std::string&amp;<\/code> function parameters? <span class=\"cpp-section-pill cpp-section-advanced\">Advanced<\/span><\/p>\n<p>Prefer <code>std::string_view<\/code> in most cases.  We cover this topic further in lesson <a href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/pass-by-const-lvalue-reference\/#stringparameter\">12.6 -- Pass by const lvalue reference<\/a>.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Improperly using <code>std::string_view<\/code><\/p>\n<p>Let&#8217;s take a look at a few cases where misusing <code>std::string_view<\/code> gets us into trouble.<\/p>\n<p>Here&#8217;s our first example:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n#include &lt;string&gt;\r\n#include &lt;string_view&gt;\r\n\r\nint main()\r\n{\r\n    std::string_view sv{};\r\n\r\n    { \/\/ create a nested block\r\n        std::string s{ \"Hello, world!\" }; \/\/ create a std::string local to this nested block\r\n        sv = s; \/\/ sv is now viewing s\r\n    } \/\/ s is destroyed here, so sv is now viewing an invalid string\r\n\r\n    std::cout &lt;&lt; sv &lt;&lt; '\\n'; \/\/ undefined behavior\r\n\r\n    return 0;\r\n}<\/code><\/pre>\n<p>In this example, we&#8217;re creating <code>std::string s<\/code> inside a nested block (don&#8217;t worry about what a nested block is yet).  Then we set <code>sv<\/code> to view <code>s<\/code>.  <code>s<\/code> is then destroyed at the end of the nested block.  <code>sv<\/code> doesn&#8217;t know that <code>s<\/code> has been destroyed.  When we then use <code>sv<\/code>, we are accessing an invalid object, and undefined behavior results.<\/p>\n<p>Here&#8217;s another variant of the same issue, where we initialize a <code>std::string_view<\/code> with the <code>std::string<\/code> return value of a function:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n#include &lt;string&gt;\r\n#include &lt;string_view&gt;\r\n\r\nstd::string getName()\r\n{\r\n    std::string s { \"Alex\" };\r\n    return s;\r\n}\r\n\r\nint main()\r\n{\r\n  std::string_view name { getName() }; \/\/ name initialized with return value of function\r\n  std::cout &lt;&lt; name &lt;&lt; '\\n'; \/\/ undefined behavior\r\n\r\n  return 0;\r\n}<\/code><\/pre>\n<p>This behaves similarly to the prior example.  The <code>getName()<\/code> function is returning a <code>std::string<\/code> containing the string &#8220;Alex&#8221;.  Return values are temporary objects that are destroyed at the end of the full expression containing the function call.  We must either use this return value immediately, or copy it to use later.<\/p>\n<p>But <code>std::string_view<\/code> doesn&#8217;t make copies.  Instead, it creates a view to the temporary return value, which is then destroyed.  That leaves our <code>std::string_view<\/code> dangling (viewing an invalid object), and printing the view results in undefined behavior.<\/p>\n<p>The following is a less-obvious variant of the above:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n#include &lt;string&gt;\r\n#include &lt;string_view&gt;\r\n\r\nint main()\r\n{\r\n    using namespace std::string_literals;\r\n    std::string_view name { \"Alex\"s }; \/\/ \"Alex\"s creates a temporary std::string\r\n    std::cout &lt;&lt; name &lt;&lt; '\\n'; \/\/ undefined behavior\r\n\r\n    return 0;\r\n}<\/code><\/pre>\n<p>A <code>std::string<\/code> literal (created via the <code>s<\/code> literal suffix) creates a temporary <code>std::string<\/code> object.  So in this case, <code>\"Alex\"s<\/code> creates a temporary <code>std::string<\/code>, which we then use as the initializer for <code>name<\/code>.  At this point, <code>name<\/code> is viewing the temporary <code>std::string<\/code>.  Then the temporary <code>std::string<\/code> is destroyed, leaving <code>name<\/code> dangling.  We get undefined behavior when we then use <code>name<\/code>.<\/p>\n<div class=\"cpp-note cpp-lightredbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Warning<\/p>\n<p>Do not initialize a <code>std::string_view<\/code> with a <code>std::string<\/code> literal, as this will leave the <code>std::string_view<\/code> dangling.<\/p>\n<p>It is okay to initialize a <code>std::string_view<\/code> with a C-style string literal or a <code>std::string_view<\/code> literal.  It&#8217;s also okay to initialize a <code>std::string_view<\/code> with a C-style string object, a <code>std::string<\/code> object, or a <code>std::string_view<\/code> object, as long as that string object outlives the view.\n<\/div>\n<p>We can also get undefined behavior when the underlying string is modified:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n#include &lt;string&gt;\r\n#include &lt;string_view&gt;\r\n\r\nint main()\r\n{\r\n    std::string s { \"Hello, world!\" };\r\n    std::string_view sv { s }; \/\/ sv is now viewing s\r\n\r\n    s = \"Hello, a!\";    \/\/ modifies s, which invalidates sv (s is still valid)\r\n    std::cout &lt;&lt; sv &lt;&lt; '\\n';   \/\/ undefined behavior\r\n\r\n    return 0;\r\n}<\/code><\/pre>\n<p>In this example, <code>sv<\/code> is again set to view <code>s<\/code>.  <code>s<\/code> is then modified.  When a <code>std::string<\/code> is modified, any views into that <code>std::string<\/code> are likely to be <strong>invalidated<\/strong>, meaning those views are now invalid or incorrect.  Using an invalidated view will result in undefined behavior.<\/p>\n<div class=\"cpp-note cpp-lightgraybackground\">\n<p class=\"cpp-note-title cpp-bottomline\">For advanced readers<\/p>\n<ul>\n<li>If the <code>std::string<\/code> reallocates memory in order to accommodate the new string data, it will return the memory used for the old string data back to the operating system.  Since the <code>std::string_view<\/code> is still viewing the old string data, it is now dangling (pointing to a now-invalid object).\n<\/li>\n<li>If the <code>std::string<\/code> does not reallocate memory, it will copy the new string data over the old string data (starting at the same memory address).  The <code>std::string_view<\/code> will now be viewing the new string data (since it was placed at the same memory address as it was viewing), but it will not realize that the length of the <code>std::string<\/code> has probably changed.  If the new string is longer than the old string, the <code>std::string_view<\/code> will now be viewing a substring of the new string (of the same length as the old string).  If the new string is shorter than the old string, the <code>std::string_view<\/code> will now be viewing a superstring of the new string (consisting of the entire new string, plus whatever garbage characters are still in the memory beyond the end of the string).\n<\/li>\n<\/ul>\n<\/div>\n<div class=\"cpp-note cpp-lightbluebackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Key insight<\/p>\n<p>Modifying a <code>std::string<\/code> is likely to invalidate all views into that <code>std::string<\/code>.\n<\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Revalidating an invalid <code>std::string_view<\/code><\/p>\n<p>Invalidated objects can often be revalidated (made valid again) by setting them back to a known good state.  For an invalidated <code>std::string_view<\/code>, we can do this by assigning the invalidated <code>std::string_view<\/code> object a valid string to view.<\/p>\n<p>Here&#8217;s the same example as prior, but we&#8217;ll revalidate <code>sv<\/code>:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n#include &lt;string&gt;\r\n#include &lt;string_view&gt;\r\n\r\nint main()\r\n{\r\n    std::string s { \"Hello, world!\" };\r\n    std::string_view sv { s }; \/\/ sv is now viewing s\r\n\r\n    s = \"Hello, universe!\";    \/\/ modifies s, which invalidates sv (s is still valid)\r\n    std::cout &lt;&lt; sv &lt;&lt; '\\n';   \/\/ undefined behavior\r\n\r\n    sv = s;                    \/\/ revalidate sv: sv is now viewing s again\r\n    std::cout &lt;&lt; sv &lt;&lt; '\\n';   \/\/ prints \"Hello, universe!\"\r\n\r\n    return 0;\r\n}<\/code><\/pre>\n<p>After <code>sv<\/code> is invalidated by the modification of <code>s<\/code>, we revalidate <code>sv<\/code> via the statement <code>sv = s<\/code>, which causes <code>sv<\/code> to become a valid view of <code>s<\/code> again.  When we print <code>sv<\/code> the second time, it prints &#8220;Hello, universe!&#8221;.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Be careful returning a <code>std::string_view<\/code><\/p>\n<p><code>std::string_view<\/code> can be used as the return value of a function.  However, this is often dangerous.<\/p>\n<p>Because local variables are destroyed at the end of the function, returning a <code>std::string_view<\/code> that is viewing a local variable will result in the returned <code>std::string_view<\/code> being invalid, and further use of that <code>std::string_view<\/code> will result in undefined behavior.  For example:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n#include &lt;string&gt;\r\n#include &lt;string_view&gt;\r\n\r\nstd::string_view getBoolName(bool b)\r\n{\r\n    std::string t { \"true\" };  \/\/ local variable\r\n    std::string f { \"false\" }; \/\/ local variable\r\n\r\n    if (b)\r\n        return t;  \/\/ return a std::string_view viewing t\r\n\r\n    return f; \/\/ return a std::string_view viewing f\r\n} \/\/ t and f are destroyed at the end of the function\r\n\r\nint main()\r\n{\r\n    std::cout &lt;&lt; getBoolName(true) &lt;&lt; ' ' &lt;&lt; getBoolName(false) &lt;&lt; '\\n'; \/\/ undefined behavior\r\n\r\n    return 0;\r\n}<\/code><\/pre>\n<p>In the above example, when <code>getBoolName(true)<\/code> is called, the function returns a <code>std::string_view<\/code> that is viewing <code>t<\/code>.  However, <code>t<\/code> is destroyed at the end of the function.  This means the returned <code>std::string_view<\/code> is viewing an object that has been destroyed.  So when the returned <code>std::string_view<\/code> is printed, undefined behavior results.<\/p>\n<p>Your compiler may or may not warn you about such cases.<\/p>\n<p>There are two main cases where a <code>std::string_view<\/code> can be returned safely.  First, because C-style string literals exist for the entire program, it&#8217;s fine (and useful) to return C-style string literals from a function that has a return type of <code>std::string_view<\/code>.<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n#include &lt;string_view&gt;\r\n\r\nstd::string_view getBoolName(bool b)\r\n{\r\n    if (b)\r\n        return \"true\";  \/\/ return a std::string_view viewing \"true\"\r\n\r\n    return \"false\"; \/\/ return a std::string_view viewing \"false\"\r\n} \/\/ \"true\" and \"false\" are not destroyed at the end of the function\r\n\r\nint main()\r\n{\r\n    std::cout &lt;&lt; getBoolName(true) &lt;&lt; ' ' &lt;&lt; getBoolName(false) &lt;&lt; '\\n'; \/\/ ok\r\n\r\n    return 0;\r\n}<\/code><\/pre>\n<p>This prints:<\/p>\n<pre>\ntrue false\r\n<\/pre>\n<p>When <code>getBoolName(true)<\/code> is called, the function will return a <code>std::string_view<\/code> viewing the C-style string <code>\"true\"<\/code>.  Because <code>\"true\"<\/code> exists for the entire program, there&#8217;s no problem when we use the returned <code>std::string_view<\/code> to print <code>\"true\"<\/code> within <code>main()<\/code>.<\/p>\n<p>Second, it is generally okay to return a function parameter of type <code>std::string_view<\/code>:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n#include &lt;string&gt;\r\n#include &lt;string_view&gt;\r\n\r\nstd::string_view firstAlphabetical(std::string_view s1, std::string_view s2)\r\n{\r\n    if (s1 &lt; s2)\r\n        return s1;\r\n    return s2;\r\n}\r\n\r\nint main()\r\n{\r\n    std::string a { \"World\" };\r\n    std::string b { \"Hello\" };\r\n\r\n    std::cout &lt;&lt; firstAlphabetical(a, b) &lt;&lt; '\\n'; \/\/ prints \"Hello\"\r\n\r\n    return 0;\r\n}<\/code><\/pre>\n<p>It may be less obvious why this is okay.  First, note that arguments <code>a<\/code> and <code>b<\/code> exist in the scope of the caller.  When the function is called, function parameter <code>s1<\/code> is a view into <code>a<\/code>, and function parameter <code>s2<\/code> is a view into <code>b<\/code>.  When the function returns either <code>s1<\/code> or <code>s2<\/code>, it is returning a view into <code>a<\/code> or <code>b<\/code> back to the caller.  Since <code>a<\/code> and <code>b<\/code> still exist at this point, it&#8217;s fine to use the returned <code>std::string_view<\/code> into <code>a<\/code> or <code>b<\/code>.<\/p>\n<p>There is one important subtlety here.  If the argument is a temporary object (that will be destroyed at the end of the full expression containing the function call), the <code>std::string_view<\/code> return value must be used in the same expression.  After that point, the temporary is destroyed and the std::string_view is left dangling.<\/p>\n<div class=\"cpp-note cpp-lightredbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Warning<\/p>\n<p>If an argument is a temporary that is destroyed at the end of the full expression containing the function call, the returned <code>std::string_view<\/code> must be used immediately, as it will be left dangling after the temporary is destroyed.\n<\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">View modification functions<\/p>\n<p>Consider a window in your house, looking at an electric car sitting on the street. You can look through the window and see the car, but you can\u2019t touch or move the car. Your window just provides a view to the car, which is a completely separate object.<\/p>\n<p>Many windows have curtains, which allow us to modify our view.  We can close either the left or right curtain to reduce what we can see.  We don&#8217;t change what&#8217;s outside, we just reduce the visible area.<\/p>\n<p>Because <code>std::string_view<\/code> is a view, it contains functions that let us modify our view by &#8220;closing the curtains&#8221;.  This does not modify the string being viewed in any way, just the view itself.<\/p>\n<ul>\n<li>The <code>remove_prefix()<\/code> member function removes characters from the left side of the view.\n<\/li>\n<li>The <code>remove_suffix()<\/code> member function removes characters from the right side of the view.\n<\/li>\n<\/ul>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n#include &lt;string_view&gt;\r\n\r\nint main()\r\n{\r\n\tstd::string_view str{ \"Peach\" };\r\n\tstd::cout &lt;&lt; str &lt;&lt; '\\n';\r\n\r\n\t\/\/ Remove 1 character from the left side of the view\r\n\tstr.remove_prefix(1);\r\n\tstd::cout &lt;&lt; str &lt;&lt; '\\n';\r\n\r\n\t\/\/ Remove 2 characters from the right side of the view\r\n\tstr.remove_suffix(2);\r\n\tstd::cout &lt;&lt; str &lt;&lt; '\\n';\r\n\r\n\tstr = \"Peach\"; \/\/ reset the view\r\n\tstd::cout &lt;&lt; str &lt;&lt; '\\n';\r\n\r\n\treturn 0;\r\n}<\/code><\/pre>\n<p>This program produces the following output:<\/p>\n<pre>\nPeach\r\neach\r\nea\r\nPeach\r\n<\/pre>\n<p>Unlike real curtains, once <code>remove_prefix()<\/code> and <code>remove_suffix()<\/code> have been called, the only way to reset the view is by reassigning the source string to it again.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\"><code>std::string_view<\/code> can view a substring<\/p>\n<p>This brings up an important use of <code>std::string_view<\/code>.  While <code>std::string_view<\/code> can be used to view an entire string without making a copy, they are also useful when we want to view a substring without making a copy.  A <strong>substring<\/strong> is a contiguous sequence of characters within an existing string.  For example, given the string &#8220;snowball&#8221;, some substrings are &#8220;snow&#8221;, &#8220;all&#8221;, and &#8220;now&#8221;.  &#8220;owl&#8221; is not a substring of &#8220;snowball&#8221; because these characters do not appear contiguously in &#8220;snowball&#8221;.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\"><code>std::string_view<\/code> may or may not be null-terminated<\/p>\n<p>The ability to view just a substring of a larger string comes with one consequence of note: a <code>std::string_view<\/code> may or may not be null-terminated.<\/p>\n<div class=\"cpp-note cpp-lightgraybackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Related content<\/p>\n<p>We cover what a null-terminated string is in lesson <a href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/literals\/\">5.2 -- Literals<\/a>.\n<\/p><\/div>\n<p>Consider the string &#8220;snowball&#8221;, which is null-terminated (because it is a C-style string literal, which are always null-terminated).  If a <code>std::string_view<\/code> views the whole string, then it is viewing a null-terminated string.  However, if <code>std::string_view<\/code> is only viewing the substring &#8220;now&#8221;, then that substring is not null-terminated (the next character is a &#8216;b&#8217;).<\/p>\n<div class=\"cpp-note cpp-lightbluebackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Key insight<\/p>\n<p>A C-style string literal and a <code>std::string<\/code> are always null-terminated.<br \/>\nA <code>std::string_view<\/code> may or may not be null-terminated.\n<\/div>\n<p>In almost all cases, this doesn&#8217;t matter -- a <code>std::string_view<\/code> keeps track of the length of the string or substring it is viewing, so it doesn&#8217;t need the null-terminator.  Converting a <code>std::string_view<\/code> to a <code>std::string<\/code> will work regardless of whether or not the <code>std::string_view<\/code> is null-terminated.<\/p>\n<div class=\"cpp-note cpp-lightredbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Warning<\/p>\n<p>Take care not to write any code that assumes a <code>std::string_view<\/code> is null terminated.\n<\/div>\n<div class=\"cpp-note cpp-lightbluebackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Tip<\/p>\n<p>If you have a non-null-terminated <code>std::string_view<\/code> and you need a null-terminated string for some reason, convert the <code>std::string_view<\/code> into a <code>std::string<\/code>.\n<\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\"><a name=\"stringvsstringview\"><\/a>A quick guide on when to use <code>std::string<\/code> vs <code>std::string_view<\/code> <a href=\"#stringvsstringview\"><i class=\"fa fa-link\" style=\"font-size: 0.8em;\"><\/i><\/a><\/p>\n<p>This guide is not meant to be comprehensive, but is intended to highlight the most common cases:<\/p>\n<p><strong>Variables<\/strong><\/p>\n<p>Use a <code>std::string<\/code> variable when:<\/p>\n<ul>\n<li>You need a string that you can modify.\n<\/li>\n<li>You need to store user-inputted text.\n<\/li>\n<li>You need to store the return value of a function that returns a <code>std::string<\/code>.\n<\/li>\n<\/ul>\n<p>Use a <code>std::string_view<\/code> variable when:<\/p>\n<ul>\n<li>You need read-only access to part or all of a string that already exists elsewhere and will not be modified or destroyed before use of the <code>std::string_view<\/code> is complete.\n<\/li>\n<li>You need a symbolic constant for a C-style string.\n<\/li>\n<li>You need to continue viewing the return value of a function that returns a C-style string or a non-dangling <code>std::string_view<\/code>.\n<\/li>\n<\/ul>\n<p><strong>Function parameters<\/strong><\/p>\n<p>Use a <code>std::string<\/code> function parameter when:<\/p>\n<ul>\n<li>The function needs to modify the string passed in as an argument without affecting the caller.  This is rare.\n<\/li>\n<li>You are using language standard C++14 or older and aren&#8217;t comfortable using references yet.\n<\/li>\n<\/ul>\n<p>Use a <code>std::string_view<\/code> function parameter when:<\/p>\n<ul>\n<li>The function needs a read-only string.\n<\/li>\n<li>The function needs to work with non-null-terminated strings.\n<\/li>\n<\/ul>\n<div class=\"cpp-note cpp-lightgraybackground\">\n<p class=\"cpp-note-title cpp-bottomline\">For advanced readers<\/p>\n<p>Also see  <a href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/pass-by-const-lvalue-reference\/#stringparameter\">12.6 -- Pass by const lvalue reference<\/a>.<\/p>\n<p>Use a <code>const std::string&amp;<\/code> function parameter when:<\/p>\n<ul>\n<li>You are using language standard C++14 or older, and the function needs a read-only string to work with (as <code>std::string_view<\/code> is not available until C++17).\n<\/li>\n<li>You are calling other functions that require a <code>const std::string<\/code>, <code>const std::string&amp;<\/code>, or const C-style string (as <code>std::string_view<\/code> may not be null-terminated).\n<\/li>\n<\/ul>\n<p>Use a <code>std::string&amp;<\/code> function parameter when:<\/p>\n<ul>\n<li>You are using a <code>std::string<\/code> as an out-parameter (see <a href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/in-and-out-parameters\/\">12.13 -- In and out parameters<\/a>).\n<\/li>\n<li>You are calling other functions that require a <code>std::string&amp;<\/code>, or non-const C-style string.\n<\/li>\n<\/ul>\n<\/div>\n<p><strong>Return types<\/strong><\/p>\n<p>Use a <code>std::string<\/code> return type when:<\/p>\n<ul>\n<li>The return value is a <code>std::string<\/code> local variable or function parameter.\n<\/li>\n<li>The return value is a function call or operator that returns a <code>std::string<\/code> by value.\n<\/li>\n<\/ul>\n<p>Use a <code>std::string_view<\/code> return type when:<\/p>\n<ul>\n<li>The function returns a C-style string literal or local <code>std::string_view<\/code> that has been initialized with a C-style string literal.\n<\/li>\n<li>The function returns a <code>std::string_view<\/code> parameter.\n<\/li>\n<\/ul>\n<div class=\"cpp-note cpp-lightgraybackground\">\n<p class=\"cpp-note-title cpp-bottomline\">For advanced readers<\/p>\n<p>See lesson <a href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/return-by-reference-and-return-by-address\/\">12.12 -- Return by reference and return by address<\/a> for more information on returning reference types.<\/p>\n<p>Use a <code>std::string_view<\/code> return type when:<\/p>\n<ul>\n<li>Writing an accessor for a <code>std::string_view<\/code> member.\n<\/li>\n<\/ul>\n<p>Use a <code>std::string&amp;<\/code> return type when:<\/p>\n<ul>\n<li>The function returns a <code>std::string&amp;<\/code> parameter.\n<\/li>\n<\/ul>\n<p>Use a <code>const std::string&amp;<\/code> return type when:<\/p>\n<ul>\n<li>The function returns a <code>const std::string&amp;<\/code> parameter.\n<\/li>\n<li>Writing an accessor for a <code>std::string<\/code> or <code>const std::string<\/code> member.\n<\/li>\n<li>The function returns a static (local or global) <code>const std::string<\/code>.\n<\/li>\n<\/ul>\n<\/div>\n<p><strong>Insights<\/strong><\/p>\n<p>Things to remember about <code>std::string<\/code>:<\/p>\n<ul>\n<li>Initializing and copying <code>std::string<\/code> is expensive, so avoid this as much as possible.\n<\/li>\n<li>Avoid passing <code>std::string<\/code> by value, as this makes a copy.\n<\/li>\n<li>If possible, avoid creating short-lived <code>std::string<\/code> objects.\n<\/li>\n<li>Modifying a <code>std::string<\/code> will invalidate any views to that string.\n<\/li>\n<li>It is okay to return a local <code>std::string<\/code> by value.\n<\/li>\n<\/ul>\n<p>Things to remember about <code>std::string_view<\/code>:<\/p>\n<ul>\n<li><code>std::string_view<\/code> is typically used for passing string function parameters and returning string literals.\n<\/li>\n<li>Because C-style string literals exist for the entire program, it is always okay to set a <code>std::string_view<\/code> to a C-style string literal.\n<\/li>\n<li>When a string is destroyed, all views to that string are invalidated.\n<\/li>\n<li>Using an invalidated view (other than using assignment to revalidate the view) will cause undefined behavior.\n<\/li>\n<li>A <code>std::string_view<\/code> may or may not be null-terminated.\n<\/li>\n<\/ul>\n<div class=\"prevnext\"><div class=\"prevnext-inline\">\n\t<a class=\"nav-link\" href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/chapter-5-summary-and-quiz\/\">\n <div class=\"nav-button nav-button-next\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-chevron-circle-right\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Next lesson<\/div>\n      <div class=\"nav-button-lesson\">\n        <span class=\"nav-button-lesson-number\">5.x<\/span>Chapter 5 summary and quiz\n      <\/div>\n    <\/div>\n  <\/div><\/a>\n  \t<a class=\"nav-link\" href=\"\/https\/www.learncpp.com\/\">\n  <div class=\"nav-button nav-button-index\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-home\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Back to table of contents<\/div>\n    <\/div>\n<\/div><\/a>\n  \t<a class=\"nav-link\" href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/introduction-to-stdstring_view\/\">\n  <div class=\"nav-button nav-button-prev\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-chevron-circle-left\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Previous lesson<\/div>\n      <div class=\"nav-button-lesson\">\n        <span class=\"nav-button-lesson-number\">5.8<\/span>Introduction to std::string_view\n      <\/div>\n    <\/div>\n  <\/div><\/a>\n  <\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>In prior lessons, we introduced two string types: std::string () and std::string_view (). Because std::string_view is our first encounter with a view type, we&#8217;re going to spend some additional time discussing it further. We will focus on how to use std::string_view safely, and provide some examples illustrating how it can &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[3],"tags":[],"_links":{"self":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/13204"}],"collection":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/comments?post=13204"}],"version-history":[{"count":50,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/13204\/revisions"}],"predecessor-version":[{"id":18069,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/13204\/revisions\/18069"}],"wp:attachment":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/media?parent=13204"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/categories?post=13204"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/tags?post=13204"}],"curies":[{"name":"wp","href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/api.w.org\/{rel}","templated":true}]}}