Is it legal to static_cast a string_view to a string












8















My question is motivated by this answer on stackoverflow, https://stackoverflow.com/a/48082010/5360439. To quote,




Q: How you convert a std::string_view to a const char*?



A: Simply do a std::string(string_view_object).c_str() to get a guaranteed null-terminated temporary copy (and clean it up at the end of the line).




Unfortunately, it constructs a new string. I am wondering if it is OK to simply do,



static_cast<string>(string_view_object).c_str()


Now, my question is:




  1. Does this constructs a new string?


  2. Is it guaranteed to return a null-terminated char sequence?



I have a small piece of code for demonstration. It seems to work fine. (See wandbox results)



#include <string>
#include <iostream>
#include <string_view>
#include <cstring>

int main()
{
std::string str{"0123456789"};
std::string_view sv(str.c_str(), 5);

std::cout << sv << std::endl;
std::cout << static_cast<std::string>(sv) << std::endl;
std::cout << strlen(static_cast<std::string>(sv).c_str()) << std::endl;
}









share|improve this question




















  • 4





    Yes, that also creates a temporary string object. I don't know how you expect to get the contents placed next to a NUL character without having a copy.

    – Ben Voigt
    1 hour ago






  • 2





    static_cast<T>(o) is pretty much the same as T(o).

    – molbdnilo
    1 hour ago






  • 1





    Please don't add a verification that essentially answers your question after someone posted an answer. It invalidates that person's effort. If the question was answered to your satisfaction, accept that answer please. Or post another answer with your own solution. SO is a Q&A site. Questions belong at the question box, answers at the answer section.

    – StoryTeller
    1 hour ago













  • @StoryTeller Sorry, I wasn't meant to invalidate efforts from other people. I haven never answered my question before, so my first thought is to post my answer by editing the question. Thanks for explaining the rule to me.

    – JohnKoch
    56 mins ago











  • No worries. I know no ill will was present. Also don't be afraid to answer your own questions if you figured something useful out for yourself and think others may benefit. It's highly encouraged in fact :)

    – StoryTeller
    54 mins ago
















8















My question is motivated by this answer on stackoverflow, https://stackoverflow.com/a/48082010/5360439. To quote,




Q: How you convert a std::string_view to a const char*?



A: Simply do a std::string(string_view_object).c_str() to get a guaranteed null-terminated temporary copy (and clean it up at the end of the line).




Unfortunately, it constructs a new string. I am wondering if it is OK to simply do,



static_cast<string>(string_view_object).c_str()


Now, my question is:




  1. Does this constructs a new string?


  2. Is it guaranteed to return a null-terminated char sequence?



I have a small piece of code for demonstration. It seems to work fine. (See wandbox results)



#include <string>
#include <iostream>
#include <string_view>
#include <cstring>

int main()
{
std::string str{"0123456789"};
std::string_view sv(str.c_str(), 5);

std::cout << sv << std::endl;
std::cout << static_cast<std::string>(sv) << std::endl;
std::cout << strlen(static_cast<std::string>(sv).c_str()) << std::endl;
}









share|improve this question




















  • 4





    Yes, that also creates a temporary string object. I don't know how you expect to get the contents placed next to a NUL character without having a copy.

    – Ben Voigt
    1 hour ago






  • 2





    static_cast<T>(o) is pretty much the same as T(o).

    – molbdnilo
    1 hour ago






  • 1





    Please don't add a verification that essentially answers your question after someone posted an answer. It invalidates that person's effort. If the question was answered to your satisfaction, accept that answer please. Or post another answer with your own solution. SO is a Q&A site. Questions belong at the question box, answers at the answer section.

    – StoryTeller
    1 hour ago













  • @StoryTeller Sorry, I wasn't meant to invalidate efforts from other people. I haven never answered my question before, so my first thought is to post my answer by editing the question. Thanks for explaining the rule to me.

    – JohnKoch
    56 mins ago











  • No worries. I know no ill will was present. Also don't be afraid to answer your own questions if you figured something useful out for yourself and think others may benefit. It's highly encouraged in fact :)

    – StoryTeller
    54 mins ago














8












8








8








My question is motivated by this answer on stackoverflow, https://stackoverflow.com/a/48082010/5360439. To quote,




Q: How you convert a std::string_view to a const char*?



A: Simply do a std::string(string_view_object).c_str() to get a guaranteed null-terminated temporary copy (and clean it up at the end of the line).




Unfortunately, it constructs a new string. I am wondering if it is OK to simply do,



static_cast<string>(string_view_object).c_str()


Now, my question is:




  1. Does this constructs a new string?


  2. Is it guaranteed to return a null-terminated char sequence?



I have a small piece of code for demonstration. It seems to work fine. (See wandbox results)



#include <string>
#include <iostream>
#include <string_view>
#include <cstring>

int main()
{
std::string str{"0123456789"};
std::string_view sv(str.c_str(), 5);

std::cout << sv << std::endl;
std::cout << static_cast<std::string>(sv) << std::endl;
std::cout << strlen(static_cast<std::string>(sv).c_str()) << std::endl;
}









share|improve this question
















My question is motivated by this answer on stackoverflow, https://stackoverflow.com/a/48082010/5360439. To quote,




Q: How you convert a std::string_view to a const char*?



A: Simply do a std::string(string_view_object).c_str() to get a guaranteed null-terminated temporary copy (and clean it up at the end of the line).




Unfortunately, it constructs a new string. I am wondering if it is OK to simply do,



static_cast<string>(string_view_object).c_str()


Now, my question is:




  1. Does this constructs a new string?


  2. Is it guaranteed to return a null-terminated char sequence?



I have a small piece of code for demonstration. It seems to work fine. (See wandbox results)



#include <string>
#include <iostream>
#include <string_view>
#include <cstring>

int main()
{
std::string str{"0123456789"};
std::string_view sv(str.c_str(), 5);

std::cout << sv << std::endl;
std::cout << static_cast<std::string>(sv) << std::endl;
std::cout << strlen(static_cast<std::string>(sv).c_str()) << std::endl;
}






c++ static-cast string-view






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 1 hour ago









newkid

368114




368114










asked 1 hour ago









JohnKochJohnKoch

356214




356214








  • 4





    Yes, that also creates a temporary string object. I don't know how you expect to get the contents placed next to a NUL character without having a copy.

    – Ben Voigt
    1 hour ago






  • 2





    static_cast<T>(o) is pretty much the same as T(o).

    – molbdnilo
    1 hour ago






  • 1





    Please don't add a verification that essentially answers your question after someone posted an answer. It invalidates that person's effort. If the question was answered to your satisfaction, accept that answer please. Or post another answer with your own solution. SO is a Q&A site. Questions belong at the question box, answers at the answer section.

    – StoryTeller
    1 hour ago













  • @StoryTeller Sorry, I wasn't meant to invalidate efforts from other people. I haven never answered my question before, so my first thought is to post my answer by editing the question. Thanks for explaining the rule to me.

    – JohnKoch
    56 mins ago











  • No worries. I know no ill will was present. Also don't be afraid to answer your own questions if you figured something useful out for yourself and think others may benefit. It's highly encouraged in fact :)

    – StoryTeller
    54 mins ago














  • 4





    Yes, that also creates a temporary string object. I don't know how you expect to get the contents placed next to a NUL character without having a copy.

    – Ben Voigt
    1 hour ago






  • 2





    static_cast<T>(o) is pretty much the same as T(o).

    – molbdnilo
    1 hour ago






  • 1





    Please don't add a verification that essentially answers your question after someone posted an answer. It invalidates that person's effort. If the question was answered to your satisfaction, accept that answer please. Or post another answer with your own solution. SO is a Q&A site. Questions belong at the question box, answers at the answer section.

    – StoryTeller
    1 hour ago













  • @StoryTeller Sorry, I wasn't meant to invalidate efforts from other people. I haven never answered my question before, so my first thought is to post my answer by editing the question. Thanks for explaining the rule to me.

    – JohnKoch
    56 mins ago











  • No worries. I know no ill will was present. Also don't be afraid to answer your own questions if you figured something useful out for yourself and think others may benefit. It's highly encouraged in fact :)

    – StoryTeller
    54 mins ago








4




4





Yes, that also creates a temporary string object. I don't know how you expect to get the contents placed next to a NUL character without having a copy.

– Ben Voigt
1 hour ago





Yes, that also creates a temporary string object. I don't know how you expect to get the contents placed next to a NUL character without having a copy.

– Ben Voigt
1 hour ago




2




2





static_cast<T>(o) is pretty much the same as T(o).

– molbdnilo
1 hour ago





static_cast<T>(o) is pretty much the same as T(o).

– molbdnilo
1 hour ago




1




1





Please don't add a verification that essentially answers your question after someone posted an answer. It invalidates that person's effort. If the question was answered to your satisfaction, accept that answer please. Or post another answer with your own solution. SO is a Q&A site. Questions belong at the question box, answers at the answer section.

– StoryTeller
1 hour ago







Please don't add a verification that essentially answers your question after someone posted an answer. It invalidates that person's effort. If the question was answered to your satisfaction, accept that answer please. Or post another answer with your own solution. SO is a Q&A site. Questions belong at the question box, answers at the answer section.

– StoryTeller
1 hour ago















@StoryTeller Sorry, I wasn't meant to invalidate efforts from other people. I haven never answered my question before, so my first thought is to post my answer by editing the question. Thanks for explaining the rule to me.

– JohnKoch
56 mins ago





@StoryTeller Sorry, I wasn't meant to invalidate efforts from other people. I haven never answered my question before, so my first thought is to post my answer by editing the question. Thanks for explaining the rule to me.

– JohnKoch
56 mins ago













No worries. I know no ill will was present. Also don't be afraid to answer your own questions if you figured something useful out for yourself and think others may benefit. It's highly encouraged in fact :)

– StoryTeller
54 mins ago





No worries. I know no ill will was present. Also don't be afraid to answer your own questions if you figured something useful out for yourself and think others may benefit. It's highly encouraged in fact :)

– StoryTeller
54 mins ago












2 Answers
2






active

oldest

votes


















7














static_cast<std::string>(sv) is calling the std::string::string constructor that expects any type convertible to std::string_view (more details). Therefore, yes, it's still creating a brand new std::string object.






share|improve this answer































    0














    A simple way to check if static_cast<std::string>(sv) constructs a new string is to verify if it's able to change original string.



    #include <string>
    #include <iostream>
    #include <string_view>
    #include <cstring>

    int main()
    {
    std::string str{"0123456789"};
    std::string_view sv = str;

    std::cout << sv << std::endl;
    static_cast<std::string>(sv)[0] = 'a';
    std::cout << static_cast<std::string>(sv) << std::endl;
    }


    sv remains unchanged, so it does creates a new string.



    See results on wandbox.






    share|improve this answer























      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%2f54211456%2fis-it-legal-to-static-cast-a-string-view-to-a-string%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      7














      static_cast<std::string>(sv) is calling the std::string::string constructor that expects any type convertible to std::string_view (more details). Therefore, yes, it's still creating a brand new std::string object.






      share|improve this answer




























        7














        static_cast<std::string>(sv) is calling the std::string::string constructor that expects any type convertible to std::string_view (more details). Therefore, yes, it's still creating a brand new std::string object.






        share|improve this answer


























          7












          7








          7







          static_cast<std::string>(sv) is calling the std::string::string constructor that expects any type convertible to std::string_view (more details). Therefore, yes, it's still creating a brand new std::string object.






          share|improve this answer













          static_cast<std::string>(sv) is calling the std::string::string constructor that expects any type convertible to std::string_view (more details). Therefore, yes, it's still creating a brand new std::string object.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 1 hour ago









          Mário FeroldiMário Feroldi

          1,98821236




          1,98821236

























              0














              A simple way to check if static_cast<std::string>(sv) constructs a new string is to verify if it's able to change original string.



              #include <string>
              #include <iostream>
              #include <string_view>
              #include <cstring>

              int main()
              {
              std::string str{"0123456789"};
              std::string_view sv = str;

              std::cout << sv << std::endl;
              static_cast<std::string>(sv)[0] = 'a';
              std::cout << static_cast<std::string>(sv) << std::endl;
              }


              sv remains unchanged, so it does creates a new string.



              See results on wandbox.






              share|improve this answer




























                0














                A simple way to check if static_cast<std::string>(sv) constructs a new string is to verify if it's able to change original string.



                #include <string>
                #include <iostream>
                #include <string_view>
                #include <cstring>

                int main()
                {
                std::string str{"0123456789"};
                std::string_view sv = str;

                std::cout << sv << std::endl;
                static_cast<std::string>(sv)[0] = 'a';
                std::cout << static_cast<std::string>(sv) << std::endl;
                }


                sv remains unchanged, so it does creates a new string.



                See results on wandbox.






                share|improve this answer


























                  0












                  0








                  0







                  A simple way to check if static_cast<std::string>(sv) constructs a new string is to verify if it's able to change original string.



                  #include <string>
                  #include <iostream>
                  #include <string_view>
                  #include <cstring>

                  int main()
                  {
                  std::string str{"0123456789"};
                  std::string_view sv = str;

                  std::cout << sv << std::endl;
                  static_cast<std::string>(sv)[0] = 'a';
                  std::cout << static_cast<std::string>(sv) << std::endl;
                  }


                  sv remains unchanged, so it does creates a new string.



                  See results on wandbox.






                  share|improve this answer













                  A simple way to check if static_cast<std::string>(sv) constructs a new string is to verify if it's able to change original string.



                  #include <string>
                  #include <iostream>
                  #include <string_view>
                  #include <cstring>

                  int main()
                  {
                  std::string str{"0123456789"};
                  std::string_view sv = str;

                  std::cout << sv << std::endl;
                  static_cast<std::string>(sv)[0] = 'a';
                  std::cout << static_cast<std::string>(sv) << std::endl;
                  }


                  sv remains unchanged, so it does creates a new string.



                  See results on wandbox.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 1 hour ago









                  JohnKochJohnKoch

                  356214




                  356214






























                      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%2f54211456%2fis-it-legal-to-static-cast-a-string-view-to-a-string%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

                      Magento 2 controller redirect on button click in phtml file

                      Polycentropodidae