I'm trying to use https://github.com/gdelugre/literal_ipaddr which says it is a
C++17 constexpr implementation of inet_addr / inet_aton / inet_pton
When I do:
auto ipSourceAddressTest = IPAddr::inet_pton<AF_INET>("127.0.0.1");
std::cout << "ipSourceAddressTest is " << ipSourceAddressTest.s_addr << std::endl;
This works fine. I get the IP address in decimal.
However:
std::string ipv4address;
//get ipv4address from world here
const unsigned int ipMaxSize = 200;
char ip[ipMaxSize];
std::copy(ipv4address.begin(), ipv4address.end(), ip);
auto ipSourceAddress = IPAddr::inet_pton<AF_INET>(ip);
std::cout << "ipSourceAddress is " << ipSourceAddress.s_addr << std::endl;
Remember that ipSourceAddress.s_addr is uint32_t. The value I get printed is not the IP in decimal but in fact is 4294967295 which is 111...111 in binary. So I think it is getting its value at compile time rather than runtime.
If I do
constexpr auto in_addr1 = IPAddr::inet_pton<AF_INET>(ip);
then it's understandable that its value will be deduces in compile time. But I didn't use constexpr in my variable declaration. Does auto implies constexpr?
According to https://en.cppreference.com/w/cpp/language/constexpr,
A constexpr specifier used in a function or static member variable (since C++17) declaration implies inline
so why the function inet_pton is getting its value in compile time?
iparray is uninitialized (becauseipv4addressis empty, andstd::copydoes nothing, due to that), hence using it, is undefined behavior. - Algirdas Preidžiusconstexprfunction can be called at runtime. It's only calculated at compile-time if possible. - superipbeing treated as null-terminated string (C-string) inIPAddr::inet_pton<AF_INET>(ip);? If so, it's undefined behavior, even ifipv4addressis not empty, sincestd::copywouldn't copy the null-terminator. - Algirdas Preidžiuschararrays, not pointers. - walnut