Is it legal to static_cast a string_view to a string

Multi tool use
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 aconst 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:
Does this constructs a new string?
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
add a comment |
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 aconst 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:
Does this constructs a new string?
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
4
Yes, that also creates a temporarystring
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 asT(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
add a comment |
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 aconst 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:
Does this constructs a new string?
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
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 aconst 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:
Does this constructs a new string?
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
c++ static-cast string-view
edited Jan 16 at 7:08
newkid
700417
700417
asked Jan 16 at 6:22


JohnKochJohnKoch
391216
391216
4
Yes, that also creates a temporarystring
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 asT(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
add a comment |
4
Yes, that also creates a temporarystring
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 asT(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
add a comment |
2 Answers
2
active
oldest
votes
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.
1
I'd phrase that as "yes and yes" (OP asked two questions).
– Arne Vogel
Jan 16 at 10:30
add a comment |
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.
2
You have to be careful with that "try it and see" approach particularly when it comes to strings. For exampleconst char* s = "hello";
followed by aconst_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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
1
I'd phrase that as "yes and yes" (OP asked two questions).
– Arne Vogel
Jan 16 at 10:30
add a comment |
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.
1
I'd phrase that as "yes and yes" (OP asked two questions).
– Arne Vogel
Jan 16 at 10:30
add a comment |
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.
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.
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
add a comment |
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
add a comment |
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.
2
You have to be careful with that "try it and see" approach particularly when it comes to strings. For exampleconst char* s = "hello";
followed by aconst_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
add a comment |
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.
2
You have to be careful with that "try it and see" approach particularly when it comes to strings. For exampleconst char* s = "hello";
followed by aconst_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
add a comment |
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.
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.
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 exampleconst char* s = "hello";
followed by aconst_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
add a comment |
2
You have to be careful with that "try it and see" approach particularly when it comes to strings. For exampleconst char* s = "hello";
followed by aconst_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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
B,9GMzNWfAM d3JaUtbcUhjKrjfax yi X0duAb IyqeP k9FGAhXONSzvu1D hlE,m1u08z
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 asT(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