C++ std::string_view equivalent in D?

ketmar ketmar at ketmar.no-ip.org
Wed Feb 21 10:24:39 UTC 2018


0xFFFFFFFF wrote:

> On Wednesday, 21 February 2018 at 09:21:58 UTC, 0xFFFFFFFF wrote:
>> What is the equivalent of C++17 std::string_view (an object that can 
>> refer to a constant contiguous sequence of char-like objects with the 
>> first element of the sequence at position zero) in D?
>>
>> PS: I'm getting back to D after years (since DMD 1 days). A lot changes 
>> since v1.0.
>
> Wow! Thanks guys.
> Those are handy, but I specifically want to do something like:
>
> ```
> string_view sv = "some string";
> ```
> So I can query it's size, make it point to sth else, use it in callbacks 
> etc. Of course I'm aware of scoping etc...
>
> I'm NOT doing any dynamic allocations, I just want a situation where a 
> string allocation string would be a little bit expensive.

and that is exactly what slices are for! ;-)

you are probably better to use `const(char)[]`, tho. like this:

	// don't store `s`, as it's contents may change after exiting of `myfunc`
	// (this is what `const` implies here)
	void myfunc (const(char)[] s) { ... }

	...
	string s = "test string";
	myfunc(s); // yep, this works
	s = s[2..4]; // this doesn't allocate
	myfunc(s);
	myfunc(s[3..6]); // or this, it doesn't allocate
	myfunc("abc"); // or this, doesn't allocate

you got the idea.


More information about the Digitalmars-d-learn mailing list