Date: Wed, 15 Nov 2023 21:50:39 +0000
Jason:
>
> Lénárd:
>
> > Isn't this a major ODR-violation footgun?
>
> Footgun? Yes. ODR violation? No.
It could be a cool way of turning a string_view into a C-style string:
#include <cstring> // memcpy
#include <algorithm> // min
#include <string_view> // string_view
template <typename = decltype([]{})>
char const *cstr(std::string_view const sv)
{
static char buf[64u];
size_t const len = std::min(sizeof buf - 1u, sv.size());
std::memcpy(buf, &sv.front(), len);
buf[len] ='\0';
return buf;
}
#include <cstdio> // printf
void Some_C_Library_Func(char const *const arg) // Requires a
null-terminated string
{
std::printf("They mentioned the colour %s.\n", arg);
}
int main()
{
char const colours[] = "The sky is blue, the grass is green, and
the chicks are yellow.";
std::string_view const a(colours + 11u,4u),
b(colours + 30u,5u),
c(colours + 56u,6u);
char const *const pa = cstr(a),
*const pb = cstr(b),
*const pc = cstr(c);
Some_C_Library_Func(pa);
Some_C_Library_Func(pb);
Some_C_Library_Func(pc);
}
The pointer to the string you get back from 'cstr' will be valid up
until you invoke 'cstr' from the same call site.
>
> Lénárd:
>
> > Isn't this a major ODR-violation footgun?
>
> Footgun? Yes. ODR violation? No.
It could be a cool way of turning a string_view into a C-style string:
#include <cstring> // memcpy
#include <algorithm> // min
#include <string_view> // string_view
template <typename = decltype([]{})>
char const *cstr(std::string_view const sv)
{
static char buf[64u];
size_t const len = std::min(sizeof buf - 1u, sv.size());
std::memcpy(buf, &sv.front(), len);
buf[len] ='\0';
return buf;
}
#include <cstdio> // printf
void Some_C_Library_Func(char const *const arg) // Requires a
null-terminated string
{
std::printf("They mentioned the colour %s.\n", arg);
}
int main()
{
char const colours[] = "The sky is blue, the grass is green, and
the chicks are yellow.";
std::string_view const a(colours + 11u,4u),
b(colours + 30u,5u),
c(colours + 56u,6u);
char const *const pa = cstr(a),
*const pb = cstr(b),
*const pc = cstr(c);
Some_C_Library_Func(pa);
Some_C_Library_Func(pb);
Some_C_Library_Func(pc);
}
The pointer to the string you get back from 'cstr' will be valid up
until you invoke 'cstr' from the same call site.
Received on 2023-11-15 21:50:52