Click here to Skip to main content
15,846,727 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to use std::span<char> to use both legacy C arrays and std::strings. Problem is that I can't "clear" spans correctly. Am I missing something?

What I have tried:

Consider the following code:

<pre>
void ClearSpan(std::span<char> strText)
{
	strText[0] = '\0';		// does not work with std::string
}


void main()
{
	char		cBuffer[100] = "Test";
	std::string	strBuffer("Test");

	strBuffer.reserve(100);	// size = 4, capacity = 103

	ClearSpan(cBuffer);
	ClearSpan(strBuffer);

	::strcat_s(cBuffer, _countof(cBuffer), "Test2");
	strBuffer += "Test 2";
}

I have 2 issues when using std::string:

1.) The size of strBuffer that is passed to the function is its string length, not its capacity (4 vs 103).

2.) Setting the first char to '\0' will not reset the size, so appending strings will not work correctly.
Posted
Comments
CPallini 7-Sep-22 4:33am    
In my opinion ClearSpan is a clear (pardon the pun) counter-example of std::span good usage. I won't even try to do that (you need to know the exact nature of the original object, in order to correctly act on it).
Jörn Kastner 7-Sep-22 5:00am    
Agreed that this is more an "academical" example. On the other hand, if I need to know the exact nature of the original object, what is the benefit of using an abstraction like std::span?
CPallini 7-Sep-22 7:51am    
You need to know the exact nature of the original object just in order to change the length of the sequence (actually you need the very original object in order to change it).
The abstraction is useful as a 'view' of the original object (e.g. to inspect all the sequence elements). See, for better info:
https://stackoverflow.com/questions/45723819/what-is-a-span-and-when-should-i-use-one
Greg Utas 7-Sep-22 9:32am    
You are using std::span to change the private data of a std::string, which tracks the length of its string. There is simply no way to update that length when you fiddle with the string's characters. A span is only a subset of an array and has no knowledge of any object that manages that array.
Jörn Kastner 7-Sep-22 9:43am    
So, what I really need is a writable std::string_view? Is this something C++2X offers?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900