[Xapian-tickets] [Xapian] #785: Use std::string_view whenever possible
Xapian
nobody at xapian.org
Fri Mar 31 21:18:10 BST 2023
#785: Use std::string_view whenever possible
-----------------------------+-------------------------------
Reporter: German M. Bravo | Owner: Olly Betts
Type: enhancement | Status: assigned
Priority: normal | Milestone: 1.5.0
Component: Other | Version:
Severity: normal | Resolution:
Keywords: | Blocked By:
Blocking: | Operating System: All
-----------------------------+-------------------------------
Comment (by Olly Betts):
Working on this, I've spotted something - any API method which takes a
string as a parameter and stores it internally would arguably benefit from
taking `std::string_view` because it avoids constructing a temporary
`std::string` in cases where the data isn't already a `std::string`
(notably this is always the case in the bindings; it's also the case in
C++ if you pass `const char*`).
Also this typically seems to be mostly a matter of just changing the
parameter type - we currently use `const std::string&` so the parameter
isn't modifiable inside the function anyway, and we are zero-byte safe so
don't use `c_str()` (or rely on `data()` pointing to a nul-terminated
string since C++11). The other difference I can see is that
`std::string_view::data()` can be `NULL` for an empty string, which again
shouldn't be a problem anywhere.
The one place this is more awkward is virtual methods which are in the API
for users to override - I think it's worth changing these too, and suggest
users overriding such methods in their code use a construct like this to
support old and new API versions (along which checking the code using the
parameter):
{{{
// XAPIAN_AT_LEAST was added in 1.4.2
#if defined(XAPIAN_AT_LEAST) && XAPIAN_AT_LEAST(1,5,0)
# define STRING_TYPE std::string_view
#else
# define STRING_TYPE const std::string&
#endif
// ...
class MyExpandDecider : public Xapian::ExpandDecider {
public:
bool operator()(STRING_TYPE term) const {
// ...
}
};
}}}
We could even define `XAPIAN_STRING_TYPE` for new versions, but none of
the 1.4.x releases made so far would define that for you so then you'd
need something like this, which doesn't really seem better than the above:
{{{
#ifndef XAPIAN_STRING_TYPE
# define XAPIAN_STRING_TYPE const std::string&
#endif
}}}
--
Ticket URL: <https://trac.xapian.org/ticket/785#comment:9>
Xapian <https://xapian.org/>
Xapian
More information about the Xapian-tickets
mailing list