Is it legal to static_cast a string_view to a string
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
1 hour ago
2
static_cast<T>(o)
is pretty much the same asT(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
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 1 hour ago
newkid
368114
368114
asked 1 hour ago
JohnKochJohnKoch
356214
356214
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
1 hour ago
2
static_cast<T>(o)
is pretty much the same asT(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
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
1 hour ago
2
static_cast<T>(o)
is pretty much the same asT(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
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.
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.
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');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
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.
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.
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.
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.
answered 1 hour ago
Mário FeroldiMário Feroldi
1,98821236
1,98821236
add a comment |
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.
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.
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 1 hour ago
JohnKochJohnKoch
356214
356214
add a comment |
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');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
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');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
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');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
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');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
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
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 asT(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