Isn't the use of string_view causing undefined behavior? For example in the example code:
auto dice2 = Dice("2d10x5 + 3d6 + 10");
Since the string passed is a rvalue temporary, it's getting destructed before the string_view is accessed. So it's accessing a dangling pointer?
Same with line 10 in Dice.cpp? (I also think the static here doesn't actually do anything since it's getting destructed when the lambda finishes executing? Am I wrong? )
I'd love if someone with more experience than me would pitch it, I usually avoid string_view because of these dangling "issues", only using it in later stages as an optimization.
Sneaky edit: I was wrong, this is not undefined behavior, thanks for /u/Wurstinator for pointing it out.
Since you're using MSVC I'd also replace strtoll to from_chars just for the hell of it. this blog post was posted here recently, which introduced me to it and it looks pretty neat.
A string literal is a pointer, so it's the same as passing e.g. the literal 1 to a function. The constructor takes that pointer by value, so it's simply copied and remains alive for the call of the function.
Oh! You're absolutely right. It's also mentioned in the notes on the cppreference page. I didn't realize the lifetime of string literals worked like this (though it makes perfect sense with them being char arrays), thank you for pointing out my mistake and teaching me something.
I'd still argue against using string_view in both cases, safety in the constructor and short string optimization in both. Though these arguments are subjective and you're completely correct about it not being undefined behavior, so the use of string_view here is not wrong.
1
u/LKummer Dec 08 '18 edited Dec 08 '18
Isn't the use of
string_viewcausing undefined behavior? For example in the example code:Since the string passed is a
rvaluetemporary, it's getting destructed before thestring_viewis accessed. So it's accessing a dangling pointer?Same with line 10 in Dice.cpp? (I also think the
statichere doesn't actually do anything since it's getting destructed when the lambda finishes executing? Am I wrong? )I'd love if someone with more experience than me would pitch it, I usually avoid
string_viewbecause of these dangling "issues", only using it in later stages as an optimization.Sneaky edit: I was wrong, this is not undefined behavior, thanks for /u/Wurstinator for pointing it out.
Since you're using MSVC I'd also replace
strtolltofrom_charsjust for the hell of it. this blog post was posted here recently, which introduced me to it and it looks pretty neat.