Is std::string guaranteed not to give back memory spontaneously?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
6
down vote

favorite
2












Is it guaranteed by the standard that std::string will not give back allocated memory spontaneously if re-sized to a smaller size?



In other words:



std::string str = "Some quite long string, which needs a lot of memory";
str = "";
str = "A new quite long but smaller string"; // Guaranteed to not result in a heap allocation?


I ask because i'm depending on this to avoid heap fragmentation.










share|improve this question























  • Not sure about the overloads, but; wouldn't it result in a new string, and hence reallocating the full string?
    – Stefan
    24 mins ago










  • if the new string allocation is less than the previous allocation, no allocation occurs. If the new string requires more allocation than the current, a reallocation occurs. Similar to a std::vector.
    – Samer Tufail
    22 mins ago










  • Strings reuse their buffers when assigned to shorter strings, so in your program there is only one allocation for the string. Unfortunately I can't find conveniently any citation from the standard on mobile
    – Fureeish
    20 mins ago










  • Even if a string did "give back memory spontaneously", that is insufficient to avoid heap fragmentation. A string uses an allocator (by default, an object of type std::allocator<char>, but that can be changed) to allocate and deallocate memory, and the allocator may use a lower-level mechanism again (e.g. variants of operators new and delete) to actually allocate and deallocate. If any of those steps elect to not release memory to the lower-level layer, there is potential impact on heap fragmentation.
    – Peter
    7 mins ago














up vote
6
down vote

favorite
2












Is it guaranteed by the standard that std::string will not give back allocated memory spontaneously if re-sized to a smaller size?



In other words:



std::string str = "Some quite long string, which needs a lot of memory";
str = "";
str = "A new quite long but smaller string"; // Guaranteed to not result in a heap allocation?


I ask because i'm depending on this to avoid heap fragmentation.










share|improve this question























  • Not sure about the overloads, but; wouldn't it result in a new string, and hence reallocating the full string?
    – Stefan
    24 mins ago










  • if the new string allocation is less than the previous allocation, no allocation occurs. If the new string requires more allocation than the current, a reallocation occurs. Similar to a std::vector.
    – Samer Tufail
    22 mins ago










  • Strings reuse their buffers when assigned to shorter strings, so in your program there is only one allocation for the string. Unfortunately I can't find conveniently any citation from the standard on mobile
    – Fureeish
    20 mins ago










  • Even if a string did "give back memory spontaneously", that is insufficient to avoid heap fragmentation. A string uses an allocator (by default, an object of type std::allocator<char>, but that can be changed) to allocate and deallocate memory, and the allocator may use a lower-level mechanism again (e.g. variants of operators new and delete) to actually allocate and deallocate. If any of those steps elect to not release memory to the lower-level layer, there is potential impact on heap fragmentation.
    – Peter
    7 mins ago












up vote
6
down vote

favorite
2









up vote
6
down vote

favorite
2






2





Is it guaranteed by the standard that std::string will not give back allocated memory spontaneously if re-sized to a smaller size?



In other words:



std::string str = "Some quite long string, which needs a lot of memory";
str = "";
str = "A new quite long but smaller string"; // Guaranteed to not result in a heap allocation?


I ask because i'm depending on this to avoid heap fragmentation.










share|improve this question















Is it guaranteed by the standard that std::string will not give back allocated memory spontaneously if re-sized to a smaller size?



In other words:



std::string str = "Some quite long string, which needs a lot of memory";
str = "";
str = "A new quite long but smaller string"; // Guaranteed to not result in a heap allocation?


I ask because i'm depending on this to avoid heap fragmentation.







c++ language-lawyer heap-memory stdstring






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 4 mins ago

























asked 27 mins ago









Martin G

8,75555058




8,75555058











  • Not sure about the overloads, but; wouldn't it result in a new string, and hence reallocating the full string?
    – Stefan
    24 mins ago










  • if the new string allocation is less than the previous allocation, no allocation occurs. If the new string requires more allocation than the current, a reallocation occurs. Similar to a std::vector.
    – Samer Tufail
    22 mins ago










  • Strings reuse their buffers when assigned to shorter strings, so in your program there is only one allocation for the string. Unfortunately I can't find conveniently any citation from the standard on mobile
    – Fureeish
    20 mins ago










  • Even if a string did "give back memory spontaneously", that is insufficient to avoid heap fragmentation. A string uses an allocator (by default, an object of type std::allocator<char>, but that can be changed) to allocate and deallocate memory, and the allocator may use a lower-level mechanism again (e.g. variants of operators new and delete) to actually allocate and deallocate. If any of those steps elect to not release memory to the lower-level layer, there is potential impact on heap fragmentation.
    – Peter
    7 mins ago
















  • Not sure about the overloads, but; wouldn't it result in a new string, and hence reallocating the full string?
    – Stefan
    24 mins ago










  • if the new string allocation is less than the previous allocation, no allocation occurs. If the new string requires more allocation than the current, a reallocation occurs. Similar to a std::vector.
    – Samer Tufail
    22 mins ago










  • Strings reuse their buffers when assigned to shorter strings, so in your program there is only one allocation for the string. Unfortunately I can't find conveniently any citation from the standard on mobile
    – Fureeish
    20 mins ago










  • Even if a string did "give back memory spontaneously", that is insufficient to avoid heap fragmentation. A string uses an allocator (by default, an object of type std::allocator<char>, but that can be changed) to allocate and deallocate memory, and the allocator may use a lower-level mechanism again (e.g. variants of operators new and delete) to actually allocate and deallocate. If any of those steps elect to not release memory to the lower-level layer, there is potential impact on heap fragmentation.
    – Peter
    7 mins ago















Not sure about the overloads, but; wouldn't it result in a new string, and hence reallocating the full string?
– Stefan
24 mins ago




Not sure about the overloads, but; wouldn't it result in a new string, and hence reallocating the full string?
– Stefan
24 mins ago












if the new string allocation is less than the previous allocation, no allocation occurs. If the new string requires more allocation than the current, a reallocation occurs. Similar to a std::vector.
– Samer Tufail
22 mins ago




if the new string allocation is less than the previous allocation, no allocation occurs. If the new string requires more allocation than the current, a reallocation occurs. Similar to a std::vector.
– Samer Tufail
22 mins ago












Strings reuse their buffers when assigned to shorter strings, so in your program there is only one allocation for the string. Unfortunately I can't find conveniently any citation from the standard on mobile
– Fureeish
20 mins ago




Strings reuse their buffers when assigned to shorter strings, so in your program there is only one allocation for the string. Unfortunately I can't find conveniently any citation from the standard on mobile
– Fureeish
20 mins ago












Even if a string did "give back memory spontaneously", that is insufficient to avoid heap fragmentation. A string uses an allocator (by default, an object of type std::allocator<char>, but that can be changed) to allocate and deallocate memory, and the allocator may use a lower-level mechanism again (e.g. variants of operators new and delete) to actually allocate and deallocate. If any of those steps elect to not release memory to the lower-level layer, there is potential impact on heap fragmentation.
– Peter
7 mins ago




Even if a string did "give back memory spontaneously", that is insufficient to avoid heap fragmentation. A string uses an allocator (by default, an object of type std::allocator<char>, but that can be changed) to allocate and deallocate memory, and the allocator may use a lower-level mechanism again (e.g. variants of operators new and delete) to actually allocate and deallocate. If any of those steps elect to not release memory to the lower-level layer, there is potential impact on heap fragmentation.
– Peter
7 mins ago












2 Answers
2






active

oldest

votes

















up vote
7
down vote













No guarantee whatsoever:




[string.capacity]/7



Effects: Alters the length of the string designated by *this as follows:



(7.1) If n <= size(), the function replaces the string designated by *this with a string of length n whose elements are a copy of the initial elements of the original string designated by *this.

(7.2) If n > size(), the function replaces the string designated by *this with a string of length n whose first size() elements are a copy of the original string designated by *this, and whose remaining elements are all initialized to c.




The emphasized part show that the Committee let the implementation choose freely between an invalidating operation and a more conservative one.






share|improve this answer






















  • Op wasn't using resize, but assigning multiple literals
    – Caleth
    34 secs ago

















up vote
4
down vote













CPP reference states that assignment from a pointer-to-char




Replaces the contents with those of null-terminated character string pointed to by s as if by *this = basic_string(s), which involves a call to Traits::length(s).




This "as if" actually boils down to an rvalue assignment, so the following scenario is quite possible:



  1. A fresh temporary string is created.

  2. This string steals its contents as via assignment to an rvalue reference.





share|improve this answer






















  • cppreference is usually reliable, but the quoted statement implies that there is a guaranteed buffer replacement, which is bollocks. Other than that it's a good conceptual model. But it's just marginally simpler than the standard's description, quoted in YSC's answer, which would therefore be preferable.
    – Cheers and hth. - Alf
    7 mins ago







  • 1




    @Cheersandhth.-Alf cppreference is paraphrasing the standard [string.cons]
    – Caleth
    1 min ago










  • @Cheersandhth.-Alf Well its written in the C++17 standard at § 24.3.2.2 27 YSC's answer is about using resize().
    – Galik
    1 min 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',
convertImagesToLinks: true,
noModals: false,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
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%2f52495704%2fis-stdstring-guaranteed-not-to-give-back-memory-spontaneously%23new-answer', 'question_page');

);

Post as a guest






























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
7
down vote













No guarantee whatsoever:




[string.capacity]/7



Effects: Alters the length of the string designated by *this as follows:



(7.1) If n <= size(), the function replaces the string designated by *this with a string of length n whose elements are a copy of the initial elements of the original string designated by *this.

(7.2) If n > size(), the function replaces the string designated by *this with a string of length n whose first size() elements are a copy of the original string designated by *this, and whose remaining elements are all initialized to c.




The emphasized part show that the Committee let the implementation choose freely between an invalidating operation and a more conservative one.






share|improve this answer






















  • Op wasn't using resize, but assigning multiple literals
    – Caleth
    34 secs ago














up vote
7
down vote













No guarantee whatsoever:




[string.capacity]/7



Effects: Alters the length of the string designated by *this as follows:



(7.1) If n <= size(), the function replaces the string designated by *this with a string of length n whose elements are a copy of the initial elements of the original string designated by *this.

(7.2) If n > size(), the function replaces the string designated by *this with a string of length n whose first size() elements are a copy of the original string designated by *this, and whose remaining elements are all initialized to c.




The emphasized part show that the Committee let the implementation choose freely between an invalidating operation and a more conservative one.






share|improve this answer






















  • Op wasn't using resize, but assigning multiple literals
    – Caleth
    34 secs ago












up vote
7
down vote










up vote
7
down vote









No guarantee whatsoever:




[string.capacity]/7



Effects: Alters the length of the string designated by *this as follows:



(7.1) If n <= size(), the function replaces the string designated by *this with a string of length n whose elements are a copy of the initial elements of the original string designated by *this.

(7.2) If n > size(), the function replaces the string designated by *this with a string of length n whose first size() elements are a copy of the original string designated by *this, and whose remaining elements are all initialized to c.




The emphasized part show that the Committee let the implementation choose freely between an invalidating operation and a more conservative one.






share|improve this answer














No guarantee whatsoever:




[string.capacity]/7



Effects: Alters the length of the string designated by *this as follows:



(7.1) If n <= size(), the function replaces the string designated by *this with a string of length n whose elements are a copy of the initial elements of the original string designated by *this.

(7.2) If n > size(), the function replaces the string designated by *this with a string of length n whose first size() elements are a copy of the original string designated by *this, and whose remaining elements are all initialized to c.




The emphasized part show that the Committee let the implementation choose freely between an invalidating operation and a more conservative one.







share|improve this answer














share|improve this answer



share|improve this answer








edited 17 mins ago

























answered 23 mins ago









YSC

17.1k33986




17.1k33986











  • Op wasn't using resize, but assigning multiple literals
    – Caleth
    34 secs ago
















  • Op wasn't using resize, but assigning multiple literals
    – Caleth
    34 secs ago















Op wasn't using resize, but assigning multiple literals
– Caleth
34 secs ago




Op wasn't using resize, but assigning multiple literals
– Caleth
34 secs ago












up vote
4
down vote













CPP reference states that assignment from a pointer-to-char




Replaces the contents with those of null-terminated character string pointed to by s as if by *this = basic_string(s), which involves a call to Traits::length(s).




This "as if" actually boils down to an rvalue assignment, so the following scenario is quite possible:



  1. A fresh temporary string is created.

  2. This string steals its contents as via assignment to an rvalue reference.





share|improve this answer






















  • cppreference is usually reliable, but the quoted statement implies that there is a guaranteed buffer replacement, which is bollocks. Other than that it's a good conceptual model. But it's just marginally simpler than the standard's description, quoted in YSC's answer, which would therefore be preferable.
    – Cheers and hth. - Alf
    7 mins ago







  • 1




    @Cheersandhth.-Alf cppreference is paraphrasing the standard [string.cons]
    – Caleth
    1 min ago










  • @Cheersandhth.-Alf Well its written in the C++17 standard at § 24.3.2.2 27 YSC's answer is about using resize().
    – Galik
    1 min ago















up vote
4
down vote













CPP reference states that assignment from a pointer-to-char




Replaces the contents with those of null-terminated character string pointed to by s as if by *this = basic_string(s), which involves a call to Traits::length(s).




This "as if" actually boils down to an rvalue assignment, so the following scenario is quite possible:



  1. A fresh temporary string is created.

  2. This string steals its contents as via assignment to an rvalue reference.





share|improve this answer






















  • cppreference is usually reliable, but the quoted statement implies that there is a guaranteed buffer replacement, which is bollocks. Other than that it's a good conceptual model. But it's just marginally simpler than the standard's description, quoted in YSC's answer, which would therefore be preferable.
    – Cheers and hth. - Alf
    7 mins ago







  • 1




    @Cheersandhth.-Alf cppreference is paraphrasing the standard [string.cons]
    – Caleth
    1 min ago










  • @Cheersandhth.-Alf Well its written in the C++17 standard at § 24.3.2.2 27 YSC's answer is about using resize().
    – Galik
    1 min ago













up vote
4
down vote










up vote
4
down vote









CPP reference states that assignment from a pointer-to-char




Replaces the contents with those of null-terminated character string pointed to by s as if by *this = basic_string(s), which involves a call to Traits::length(s).




This "as if" actually boils down to an rvalue assignment, so the following scenario is quite possible:



  1. A fresh temporary string is created.

  2. This string steals its contents as via assignment to an rvalue reference.





share|improve this answer














CPP reference states that assignment from a pointer-to-char




Replaces the contents with those of null-terminated character string pointed to by s as if by *this = basic_string(s), which involves a call to Traits::length(s).




This "as if" actually boils down to an rvalue assignment, so the following scenario is quite possible:



  1. A fresh temporary string is created.

  2. This string steals its contents as via assignment to an rvalue reference.






share|improve this answer














share|improve this answer



share|improve this answer








edited 19 mins ago









lubgr

7,22021441




7,22021441










answered 22 mins ago









bipll

7,1721821




7,1721821











  • cppreference is usually reliable, but the quoted statement implies that there is a guaranteed buffer replacement, which is bollocks. Other than that it's a good conceptual model. But it's just marginally simpler than the standard's description, quoted in YSC's answer, which would therefore be preferable.
    – Cheers and hth. - Alf
    7 mins ago







  • 1




    @Cheersandhth.-Alf cppreference is paraphrasing the standard [string.cons]
    – Caleth
    1 min ago










  • @Cheersandhth.-Alf Well its written in the C++17 standard at § 24.3.2.2 27 YSC's answer is about using resize().
    – Galik
    1 min ago

















  • cppreference is usually reliable, but the quoted statement implies that there is a guaranteed buffer replacement, which is bollocks. Other than that it's a good conceptual model. But it's just marginally simpler than the standard's description, quoted in YSC's answer, which would therefore be preferable.
    – Cheers and hth. - Alf
    7 mins ago







  • 1




    @Cheersandhth.-Alf cppreference is paraphrasing the standard [string.cons]
    – Caleth
    1 min ago










  • @Cheersandhth.-Alf Well its written in the C++17 standard at § 24.3.2.2 27 YSC's answer is about using resize().
    – Galik
    1 min ago
















cppreference is usually reliable, but the quoted statement implies that there is a guaranteed buffer replacement, which is bollocks. Other than that it's a good conceptual model. But it's just marginally simpler than the standard's description, quoted in YSC's answer, which would therefore be preferable.
– Cheers and hth. - Alf
7 mins ago





cppreference is usually reliable, but the quoted statement implies that there is a guaranteed buffer replacement, which is bollocks. Other than that it's a good conceptual model. But it's just marginally simpler than the standard's description, quoted in YSC's answer, which would therefore be preferable.
– Cheers and hth. - Alf
7 mins ago





1




1




@Cheersandhth.-Alf cppreference is paraphrasing the standard [string.cons]
– Caleth
1 min ago




@Cheersandhth.-Alf cppreference is paraphrasing the standard [string.cons]
– Caleth
1 min ago












@Cheersandhth.-Alf Well its written in the C++17 standard at § 24.3.2.2 27 YSC's answer is about using resize().
– Galik
1 min ago





@Cheersandhth.-Alf Well its written in the C++17 standard at § 24.3.2.2 27 YSC's answer is about using resize().
– Galik
1 min ago


















 

draft saved


draft discarded















































 


draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52495704%2fis-stdstring-guaranteed-not-to-give-back-memory-spontaneously%23new-answer', 'question_page');

);

Post as a guest













































































Comments

Popular posts from this blog

What does second last employer means? [closed]

List of Gilmore Girls characters

Confectionery