Why does std::string_view create a dangling view in a ternary expression?Why is “using namespace std;” considered bad practice?Purpose of returning by const value?Why does changing 0.1f to 0 slow down performance by 10x?Why does this let me get a non-const pointer to a field of a const object?How exactly is std::string_view faster than const std::string&?Why is there no support for concatenating std::string and std::string_view?What drawbacks would exist if std::string::substr returned std::string_view?Why pass string_view by value? And why can't Visual Studio optimize this?Is std::move safe in an arguments list when the argument is forwarded, not move constructed?Comparing a std::string_view and a substring string_view

What is the "ls" directory in my home directory?

Prisoner on alien planet escapes by making up a story about ghost companions and wins the war

How could empty set be unique if it could be vacuously false

Is the specular reflection on a polished gold sphere white or gold in colour?

Find All Possible Unique Combinations of Letters in a Word

Covering index used despite missing column

What is the meaning of "понаехать"?

Greeting with "Ho"

Encounter design and XP thresholds

What are Elsa's reasons for selecting the Holy Grail on behalf of Donovan?

Why does independence imply zero correlation?

Find the common ancestor between two nodes of a tree

In the US, can a former president run again?

Are there any individual aliens that have gained superpowers in the Marvel universe?

Boss wants someone else to lead a project based on the idea I presented to him

How to work with PETG? Settings, caveats, etc

What constitutes a syllable?

Rejecting an offer after accepting it just 10 days from date of joining

Drawing a second weapon as part of an attack?

When Bnei Yisroel travelled in the midbar, what happened on Shabbos?

Print one file per line using echo

Is there official documentation on directories like ~/.config and ~/.cache?

Why isn't it a compile-time error to return a nullptr as a std::string?

I just entered the USA without passport control at Atlanta airport



Why does std::string_view create a dangling view in a ternary expression?


Why is “using namespace std;” considered bad practice?Purpose of returning by const value?Why does changing 0.1f to 0 slow down performance by 10x?Why does this let me get a non-const pointer to a field of a const object?How exactly is std::string_view faster than const std::string&?Why is there no support for concatenating std::string and std::string_view?What drawbacks would exist if std::string::substr returned std::string_view?Why pass string_view by value? And why can't Visual Studio optimize this?Is std::move safe in an arguments list when the argument is forwarded, not move constructed?Comparing a std::string_view and a substring string_view






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








12















Consider a method that returns a std::string_view either from a method that returns a const std::string& or from an empty string. To my surprise, writing the method this way results in a dangling string view:



const std::string& otherMethod();

std::string_view myMethod(bool bla)
return bla ? otherMethod() : ""; // Dangling view!



https://godbolt.org/z/1Hu_p2



It seems that the compiler first puts a temporary std::string copy of the result of otherMethod() on the stack and then returns a view of this temporary copy instead of just returning a view of the reference. First I thought about a comipler bug, but both G++ and clang do this.



The fix is easy: Wrapping otherMethod into an explicit construction of string_view solves the issue:



std::string_view myMethod(bool bla) 
return bla ? std::string_view(otherMethod()) : ""; // Works as intended!



https://godbolt.org/z/Q-sEkr



Why is this the case? Why does the original code create an implicit copy without warning?










share|improve this question




























    12















    Consider a method that returns a std::string_view either from a method that returns a const std::string& or from an empty string. To my surprise, writing the method this way results in a dangling string view:



    const std::string& otherMethod();

    std::string_view myMethod(bool bla)
    return bla ? otherMethod() : ""; // Dangling view!



    https://godbolt.org/z/1Hu_p2



    It seems that the compiler first puts a temporary std::string copy of the result of otherMethod() on the stack and then returns a view of this temporary copy instead of just returning a view of the reference. First I thought about a comipler bug, but both G++ and clang do this.



    The fix is easy: Wrapping otherMethod into an explicit construction of string_view solves the issue:



    std::string_view myMethod(bool bla) 
    return bla ? std::string_view(otherMethod()) : ""; // Works as intended!



    https://godbolt.org/z/Q-sEkr



    Why is this the case? Why does the original code create an implicit copy without warning?










    share|improve this question
























      12












      12








      12


      4






      Consider a method that returns a std::string_view either from a method that returns a const std::string& or from an empty string. To my surprise, writing the method this way results in a dangling string view:



      const std::string& otherMethod();

      std::string_view myMethod(bool bla)
      return bla ? otherMethod() : ""; // Dangling view!



      https://godbolt.org/z/1Hu_p2



      It seems that the compiler first puts a temporary std::string copy of the result of otherMethod() on the stack and then returns a view of this temporary copy instead of just returning a view of the reference. First I thought about a comipler bug, but both G++ and clang do this.



      The fix is easy: Wrapping otherMethod into an explicit construction of string_view solves the issue:



      std::string_view myMethod(bool bla) 
      return bla ? std::string_view(otherMethod()) : ""; // Works as intended!



      https://godbolt.org/z/Q-sEkr



      Why is this the case? Why does the original code create an implicit copy without warning?










      share|improve this question














      Consider a method that returns a std::string_view either from a method that returns a const std::string& or from an empty string. To my surprise, writing the method this way results in a dangling string view:



      const std::string& otherMethod();

      std::string_view myMethod(bool bla)
      return bla ? otherMethod() : ""; // Dangling view!



      https://godbolt.org/z/1Hu_p2



      It seems that the compiler first puts a temporary std::string copy of the result of otherMethod() on the stack and then returns a view of this temporary copy instead of just returning a view of the reference. First I thought about a comipler bug, but both G++ and clang do this.



      The fix is easy: Wrapping otherMethod into an explicit construction of string_view solves the issue:



      std::string_view myMethod(bool bla) 
      return bla ? std::string_view(otherMethod()) : ""; // Works as intended!



      https://godbolt.org/z/Q-sEkr



      Why is this the case? Why does the original code create an implicit copy without warning?







      c++ language-lawyer c++17 dangling-pointer string-view






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 12 hours ago









      gexicidegexicide

      21.6k1767115




      21.6k1767115






















          1 Answer
          1






          active

          oldest

          votes


















          17














          Because that's how the conditional operator works.



          You're invoking ?: on two operands, one of which is an lvalue of type std::string const and the other is an lvalue of type char const[1]. The language rule for the conditional operator is... really complicated. The relevant rule is:




          Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification, an attempt is made to form an implicit conversion sequence from each of those operands to the type of the other. [ Note: Properties such as access, whether an operand is a bit-field, or whether a conversion function is deleted are ignored for that determination. — end note ] Attempts are made to form an implicit conversion sequence from an operand expression E1 of type T1 to a target type related to the type T2 of the operand expression E2 as follows:



          • If E2 is an lvalue, the target type is “lvalue reference to T2”, subject to the constraint that in the conversion the reference must bind directly ([dcl.init.ref]) to a glvalue.

          • If E2 is an xvalue, [...]


          • If E2 is a prvalue or if neither of the conversion sequences above can be formed and at least one of the operands has (possibly cv-qualified) class type:



            • if T1 and T2 are the same class type [...]

            • otherwise, if T2 is a base class of T1, [...]

            • otherwise, the target type is the type that E2 would have after applying the lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard conversions.


          Using this process, it is determined whether an implicit conversion sequence can be formed from the second operand to the target type determined for the third operand, and vice versa. If both sequences can be formed, or one can be formed but it is the ambiguous conversion sequence, the program is ill-formed. If no conversion sequence can be formed, the operands are left unchanged and further checking is performed as described below. Otherwise, if exactly one conversion sequence can be formed, that conversion is applied to the chosen operand and the converted operand is used in place of the original operand for the remainder of this subclause. [ Note: The conversion might be ill-formed even if an implicit conversion sequence could be formed. — end note ]




          Can't convert std::string const to either char const(&)[1] or char const*, but you can convert char const[1] to std::string const (the inner nested bullet)... so that's what you get. A prvalue of type std::string const. Which is to say, you're either copying one string or constructing a new one... either way, you're returning a string_view to a temporary which goes out of scope immediately.




          What you want is either what you had:



          std::string_view myMethod(bool bla) 
          return bla ? std::string_view(otherMethod()) : "";



          or:



          std::string_view myMethod(bool bla) 
          return bla ? otherMethod() : ""sv;



          The result of that conditional operator is a string_view, with both conversions being safe.






          share|improve this answer

























          • I'm sorry but this catch phrase is already taken! ;)

            – Holt
            12 hours ago






          • 2





            @Holt Well, it's the conditional operator, not the ternary operator :-P

            – Barry
            12 hours ago











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56634198%2fwhy-does-stdstring-view-create-a-dangling-view-in-a-ternary-expression%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          17














          Because that's how the conditional operator works.



          You're invoking ?: on two operands, one of which is an lvalue of type std::string const and the other is an lvalue of type char const[1]. The language rule for the conditional operator is... really complicated. The relevant rule is:




          Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification, an attempt is made to form an implicit conversion sequence from each of those operands to the type of the other. [ Note: Properties such as access, whether an operand is a bit-field, or whether a conversion function is deleted are ignored for that determination. — end note ] Attempts are made to form an implicit conversion sequence from an operand expression E1 of type T1 to a target type related to the type T2 of the operand expression E2 as follows:



          • If E2 is an lvalue, the target type is “lvalue reference to T2”, subject to the constraint that in the conversion the reference must bind directly ([dcl.init.ref]) to a glvalue.

          • If E2 is an xvalue, [...]


          • If E2 is a prvalue or if neither of the conversion sequences above can be formed and at least one of the operands has (possibly cv-qualified) class type:



            • if T1 and T2 are the same class type [...]

            • otherwise, if T2 is a base class of T1, [...]

            • otherwise, the target type is the type that E2 would have after applying the lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard conversions.


          Using this process, it is determined whether an implicit conversion sequence can be formed from the second operand to the target type determined for the third operand, and vice versa. If both sequences can be formed, or one can be formed but it is the ambiguous conversion sequence, the program is ill-formed. If no conversion sequence can be formed, the operands are left unchanged and further checking is performed as described below. Otherwise, if exactly one conversion sequence can be formed, that conversion is applied to the chosen operand and the converted operand is used in place of the original operand for the remainder of this subclause. [ Note: The conversion might be ill-formed even if an implicit conversion sequence could be formed. — end note ]




          Can't convert std::string const to either char const(&)[1] or char const*, but you can convert char const[1] to std::string const (the inner nested bullet)... so that's what you get. A prvalue of type std::string const. Which is to say, you're either copying one string or constructing a new one... either way, you're returning a string_view to a temporary which goes out of scope immediately.




          What you want is either what you had:



          std::string_view myMethod(bool bla) 
          return bla ? std::string_view(otherMethod()) : "";



          or:



          std::string_view myMethod(bool bla) 
          return bla ? otherMethod() : ""sv;



          The result of that conditional operator is a string_view, with both conversions being safe.






          share|improve this answer

























          • I'm sorry but this catch phrase is already taken! ;)

            – Holt
            12 hours ago






          • 2





            @Holt Well, it's the conditional operator, not the ternary operator :-P

            – Barry
            12 hours ago















          17














          Because that's how the conditional operator works.



          You're invoking ?: on two operands, one of which is an lvalue of type std::string const and the other is an lvalue of type char const[1]. The language rule for the conditional operator is... really complicated. The relevant rule is:




          Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification, an attempt is made to form an implicit conversion sequence from each of those operands to the type of the other. [ Note: Properties such as access, whether an operand is a bit-field, or whether a conversion function is deleted are ignored for that determination. — end note ] Attempts are made to form an implicit conversion sequence from an operand expression E1 of type T1 to a target type related to the type T2 of the operand expression E2 as follows:



          • If E2 is an lvalue, the target type is “lvalue reference to T2”, subject to the constraint that in the conversion the reference must bind directly ([dcl.init.ref]) to a glvalue.

          • If E2 is an xvalue, [...]


          • If E2 is a prvalue or if neither of the conversion sequences above can be formed and at least one of the operands has (possibly cv-qualified) class type:



            • if T1 and T2 are the same class type [...]

            • otherwise, if T2 is a base class of T1, [...]

            • otherwise, the target type is the type that E2 would have after applying the lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard conversions.


          Using this process, it is determined whether an implicit conversion sequence can be formed from the second operand to the target type determined for the third operand, and vice versa. If both sequences can be formed, or one can be formed but it is the ambiguous conversion sequence, the program is ill-formed. If no conversion sequence can be formed, the operands are left unchanged and further checking is performed as described below. Otherwise, if exactly one conversion sequence can be formed, that conversion is applied to the chosen operand and the converted operand is used in place of the original operand for the remainder of this subclause. [ Note: The conversion might be ill-formed even if an implicit conversion sequence could be formed. — end note ]




          Can't convert std::string const to either char const(&)[1] or char const*, but you can convert char const[1] to std::string const (the inner nested bullet)... so that's what you get. A prvalue of type std::string const. Which is to say, you're either copying one string or constructing a new one... either way, you're returning a string_view to a temporary which goes out of scope immediately.




          What you want is either what you had:



          std::string_view myMethod(bool bla) 
          return bla ? std::string_view(otherMethod()) : "";



          or:



          std::string_view myMethod(bool bla) 
          return bla ? otherMethod() : ""sv;



          The result of that conditional operator is a string_view, with both conversions being safe.






          share|improve this answer

























          • I'm sorry but this catch phrase is already taken! ;)

            – Holt
            12 hours ago






          • 2





            @Holt Well, it's the conditional operator, not the ternary operator :-P

            – Barry
            12 hours ago













          17












          17








          17







          Because that's how the conditional operator works.



          You're invoking ?: on two operands, one of which is an lvalue of type std::string const and the other is an lvalue of type char const[1]. The language rule for the conditional operator is... really complicated. The relevant rule is:




          Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification, an attempt is made to form an implicit conversion sequence from each of those operands to the type of the other. [ Note: Properties such as access, whether an operand is a bit-field, or whether a conversion function is deleted are ignored for that determination. — end note ] Attempts are made to form an implicit conversion sequence from an operand expression E1 of type T1 to a target type related to the type T2 of the operand expression E2 as follows:



          • If E2 is an lvalue, the target type is “lvalue reference to T2”, subject to the constraint that in the conversion the reference must bind directly ([dcl.init.ref]) to a glvalue.

          • If E2 is an xvalue, [...]


          • If E2 is a prvalue or if neither of the conversion sequences above can be formed and at least one of the operands has (possibly cv-qualified) class type:



            • if T1 and T2 are the same class type [...]

            • otherwise, if T2 is a base class of T1, [...]

            • otherwise, the target type is the type that E2 would have after applying the lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard conversions.


          Using this process, it is determined whether an implicit conversion sequence can be formed from the second operand to the target type determined for the third operand, and vice versa. If both sequences can be formed, or one can be formed but it is the ambiguous conversion sequence, the program is ill-formed. If no conversion sequence can be formed, the operands are left unchanged and further checking is performed as described below. Otherwise, if exactly one conversion sequence can be formed, that conversion is applied to the chosen operand and the converted operand is used in place of the original operand for the remainder of this subclause. [ Note: The conversion might be ill-formed even if an implicit conversion sequence could be formed. — end note ]




          Can't convert std::string const to either char const(&)[1] or char const*, but you can convert char const[1] to std::string const (the inner nested bullet)... so that's what you get. A prvalue of type std::string const. Which is to say, you're either copying one string or constructing a new one... either way, you're returning a string_view to a temporary which goes out of scope immediately.




          What you want is either what you had:



          std::string_view myMethod(bool bla) 
          return bla ? std::string_view(otherMethod()) : "";



          or:



          std::string_view myMethod(bool bla) 
          return bla ? otherMethod() : ""sv;



          The result of that conditional operator is a string_view, with both conversions being safe.






          share|improve this answer















          Because that's how the conditional operator works.



          You're invoking ?: on two operands, one of which is an lvalue of type std::string const and the other is an lvalue of type char const[1]. The language rule for the conditional operator is... really complicated. The relevant rule is:




          Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification, an attempt is made to form an implicit conversion sequence from each of those operands to the type of the other. [ Note: Properties such as access, whether an operand is a bit-field, or whether a conversion function is deleted are ignored for that determination. — end note ] Attempts are made to form an implicit conversion sequence from an operand expression E1 of type T1 to a target type related to the type T2 of the operand expression E2 as follows:



          • If E2 is an lvalue, the target type is “lvalue reference to T2”, subject to the constraint that in the conversion the reference must bind directly ([dcl.init.ref]) to a glvalue.

          • If E2 is an xvalue, [...]


          • If E2 is a prvalue or if neither of the conversion sequences above can be formed and at least one of the operands has (possibly cv-qualified) class type:



            • if T1 and T2 are the same class type [...]

            • otherwise, if T2 is a base class of T1, [...]

            • otherwise, the target type is the type that E2 would have after applying the lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard conversions.


          Using this process, it is determined whether an implicit conversion sequence can be formed from the second operand to the target type determined for the third operand, and vice versa. If both sequences can be formed, or one can be formed but it is the ambiguous conversion sequence, the program is ill-formed. If no conversion sequence can be formed, the operands are left unchanged and further checking is performed as described below. Otherwise, if exactly one conversion sequence can be formed, that conversion is applied to the chosen operand and the converted operand is used in place of the original operand for the remainder of this subclause. [ Note: The conversion might be ill-formed even if an implicit conversion sequence could be formed. — end note ]




          Can't convert std::string const to either char const(&)[1] or char const*, but you can convert char const[1] to std::string const (the inner nested bullet)... so that's what you get. A prvalue of type std::string const. Which is to say, you're either copying one string or constructing a new one... either way, you're returning a string_view to a temporary which goes out of scope immediately.




          What you want is either what you had:



          std::string_view myMethod(bool bla) 
          return bla ? std::string_view(otherMethod()) : "";



          or:



          std::string_view myMethod(bool bla) 
          return bla ? otherMethod() : ""sv;



          The result of that conditional operator is a string_view, with both conversions being safe.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 10 hours ago

























          answered 12 hours ago









          BarryBarry

          193k22352640




          193k22352640












          • I'm sorry but this catch phrase is already taken! ;)

            – Holt
            12 hours ago






          • 2





            @Holt Well, it's the conditional operator, not the ternary operator :-P

            – Barry
            12 hours ago

















          • I'm sorry but this catch phrase is already taken! ;)

            – Holt
            12 hours ago






          • 2





            @Holt Well, it's the conditional operator, not the ternary operator :-P

            – Barry
            12 hours ago
















          I'm sorry but this catch phrase is already taken! ;)

          – Holt
          12 hours ago





          I'm sorry but this catch phrase is already taken! ;)

          – Holt
          12 hours ago




          2




          2





          @Holt Well, it's the conditional operator, not the ternary operator :-P

          – Barry
          12 hours ago





          @Holt Well, it's the conditional operator, not the ternary operator :-P

          – Barry
          12 hours ago

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56634198%2fwhy-does-stdstring-view-create-a-dangling-view-in-a-ternary-expression%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          ParseJSON using SSJSUsing AMPscript with SSJS ActivitiesHow to resubscribe a user in Marketing cloud using SSJS?Pulling Subscriber Status from Lists using SSJSRetrieving Emails using SSJSProblem in updating DE using SSJSUsing SSJS to send single email in Marketing CloudError adding EmailSendDefinition using SSJS

          Кампала Садржај Географија Географија Историја Становништво Привреда Партнерски градови Референце Спољашње везе Мени за навигацију0°11′ СГШ; 32°20′ ИГД / 0.18° СГШ; 32.34° ИГД / 0.18; 32.340°11′ СГШ; 32°20′ ИГД / 0.18° СГШ; 32.34° ИГД / 0.18; 32.34МедијиПодациЗванични веб-сајту

          19. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу