Is it legal to static_cast a string_view to a string












13















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
    Jan 16 at 6:27






  • 2





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

    – molbdnilo
    Jan 16 at 6:28






  • 2





    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
    Jan 16 at 7:00













  • @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
    Jan 16 at 7:24











  • 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
    Jan 16 at 7:26
















13















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
    Jan 16 at 6:27






  • 2





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

    – molbdnilo
    Jan 16 at 6:28






  • 2





    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
    Jan 16 at 7:00













  • @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
    Jan 16 at 7:24











  • 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
    Jan 16 at 7:26














13












13








13








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 Jan 16 at 7:08









newkid

700417




700417










asked Jan 16 at 6:22









JohnKochJohnKoch

391216




391216








  • 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
    Jan 16 at 6:27






  • 2





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

    – molbdnilo
    Jan 16 at 6:28






  • 2





    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
    Jan 16 at 7:00













  • @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
    Jan 16 at 7:24











  • 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
    Jan 16 at 7:26














  • 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
    Jan 16 at 6:27






  • 2





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

    – molbdnilo
    Jan 16 at 6:28






  • 2





    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
    Jan 16 at 7:00













  • @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
    Jan 16 at 7:24











  • 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
    Jan 16 at 7:26








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
Jan 16 at 6:27





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
Jan 16 at 6:27




2




2





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

– molbdnilo
Jan 16 at 6:28





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

– molbdnilo
Jan 16 at 6:28




2




2





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
Jan 16 at 7:00







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
Jan 16 at 7:00















@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
Jan 16 at 7:24





@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
Jan 16 at 7:24













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
Jan 16 at 7:26





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
Jan 16 at 7:26












2 Answers
2






active

oldest

votes


















12














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, which in turn guarantees a null-terminated char sequence.






share|improve this answer





















  • 1





    I'd phrase that as "yes and yes" (OP asked two questions).

    – Arne Vogel
    Jan 16 at 10:30



















-3














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



















  • 2





    You have to be careful with that "try it and see" approach particularly when it comes to strings. For example const char* s = "hello"; followed by a const_cast and an attempt to modify that string by array indexing sometimes works, but actually the behaviour is undefined. The best thing to do is to check the documentation.

    – Bathsheba
    Jan 16 at 8:28













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









12














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, which in turn guarantees a null-terminated char sequence.






share|improve this answer





















  • 1





    I'd phrase that as "yes and yes" (OP asked two questions).

    – Arne Vogel
    Jan 16 at 10:30
















12














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, which in turn guarantees a null-terminated char sequence.






share|improve this answer





















  • 1





    I'd phrase that as "yes and yes" (OP asked two questions).

    – Arne Vogel
    Jan 16 at 10:30














12












12








12







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, which in turn guarantees a null-terminated char sequence.






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, which in turn guarantees a null-terminated char sequence.







share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 16 at 16:45

























answered Jan 16 at 6:28









Mário FeroldiMário Feroldi

2,08221238




2,08221238








  • 1





    I'd phrase that as "yes and yes" (OP asked two questions).

    – Arne Vogel
    Jan 16 at 10:30














  • 1





    I'd phrase that as "yes and yes" (OP asked two questions).

    – Arne Vogel
    Jan 16 at 10:30








1




1





I'd phrase that as "yes and yes" (OP asked two questions).

– Arne Vogel
Jan 16 at 10:30





I'd phrase that as "yes and yes" (OP asked two questions).

– Arne Vogel
Jan 16 at 10:30













-3














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



















  • 2





    You have to be careful with that "try it and see" approach particularly when it comes to strings. For example const char* s = "hello"; followed by a const_cast and an attempt to modify that string by array indexing sometimes works, but actually the behaviour is undefined. The best thing to do is to check the documentation.

    – Bathsheba
    Jan 16 at 8:28


















-3














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



















  • 2





    You have to be careful with that "try it and see" approach particularly when it comes to strings. For example const char* s = "hello"; followed by a const_cast and an attempt to modify that string by array indexing sometimes works, but actually the behaviour is undefined. The best thing to do is to check the documentation.

    – Bathsheba
    Jan 16 at 8:28
















-3












-3








-3







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 Jan 16 at 7:13









JohnKochJohnKoch

391216




391216








  • 2





    You have to be careful with that "try it and see" approach particularly when it comes to strings. For example const char* s = "hello"; followed by a const_cast and an attempt to modify that string by array indexing sometimes works, but actually the behaviour is undefined. The best thing to do is to check the documentation.

    – Bathsheba
    Jan 16 at 8:28
















  • 2





    You have to be careful with that "try it and see" approach particularly when it comes to strings. For example const char* s = "hello"; followed by a const_cast and an attempt to modify that string by array indexing sometimes works, but actually the behaviour is undefined. The best thing to do is to check the documentation.

    – Bathsheba
    Jan 16 at 8:28










2




2





You have to be careful with that "try it and see" approach particularly when it comes to strings. For example const char* s = "hello"; followed by a const_cast and an attempt to modify that string by array indexing sometimes works, but actually the behaviour is undefined. The best thing to do is to check the documentation.

– Bathsheba
Jan 16 at 8:28







You have to be careful with that "try it and see" approach particularly when it comes to strings. For example const char* s = "hello"; followed by a const_cast and an attempt to modify that string by array indexing sometimes works, but actually the behaviour is undefined. The best thing to do is to check the documentation.

– Bathsheba
Jan 16 at 8:28




















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

Mario Kart Wii

What does “Dominus providebit” mean?

Antonio Litta Visconti Arese