If I have a long string:
std::string data("This is a string long enough so that it is not a short string");
And then I have a view onto that string:
std::string_view dataView(std::begin(data) + 5, std::end(data) - 5);
If I move the original string:
std::string movedData(std::move(data));
Then I would expect the view dataView to remain valid.
But, this assumption does not hold if the std::string short string optimization takes effect, as the underlying memory of the string is not dynamically allocated, and the move now (underneath the hood) becomes a destructive copy operation, leaving the view invalid.
Is there a way to detect SSO (so I can take appropriate action in my class move constructor)? And does the standard make any reference to SSO?
Context
I have a class that holds a URL as a string, and then access to each of the parts of the URL is held as views into the original URL. Of course, calculating the views has a cost, but it's better to calculate it once than on each access (or that was my thought process). For a copy, you have recalculated the views, but a move (I thought) does not need to recalculate the views, as the underlying storage will be moved and thus the views will still be valid.
class URL
{
std::string url;
std::string_view schema;
std::string_view host;
std::string_view path;
// .. etc (for the multiple parts of a URL you can extract).
// Note: Parsing a URL correctly is non-trivial (handling IPV6, etc.).
// So I don't want to do it that often.
public:
// Default constructor.
URL() {}
// Normal constructor: Accept input by copy/move
URL(std::string urlInput)
: url(std::move(urlInput))
{
// Compute Views.
}
// Copy constructor.
URL(URL const& copy)
: url(copy.url)
{
// Compute Views.
}
// Move constructor
// I hoped I could simply swap the two objects.
// This works if there is no short string optimization.
URL(URL&& move) noexcept
{
swap(move);
}
// Assignment (both copy and move in one place).
// Use standard copy and swap idium.
URL operator=(URL assign) noexcept
{
swap(assign);
return *this;
}
// Faithful swap function.
void swap(URL& other) noexcept
{
using std::swap;
swap(url, other.url);
swap(schema, other.schema);
swap(host, other.host);
swap(path, other.path);
}
// Getter functions removed. But simply return std::string_view.
};
_view. This is true regardless of whether the string implementation uses SSO or not. So your assertion that your approach "works" unless SSO is used is incorrect - it has undefined behaviour, regardless. One of the "joys" of undefined behaviour is that the observed behaviour (e.g. with a particular implementation) can "work" as the programmer expects ..... until something changes (e.g. update of the implementation, building your program with a different compiler, etc).string_viewwith something that uses indices into the string to remember the starting point. Or, do that to adjust thestring_viewin your move.std::string{}.capacity()