Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a static_assert in a POD ruin the POD?

I was just wondering... Let's say I have a POD structure in C++. If I would put a static_assert in there, will it ruin the fact that it's a POD?

I know I can easily put it somewhere else, I'm just asking because I'm interested if I should or shouldn't do this...

In other words (more specific):

#include <iostream>
#include <type_traits>

struct A 
{
    void* ptr;

    static_assert(sizeof(void*) == 8, "Pointer should have size 8; platform unsupported");
};

int main()
{
    // Is it guaranteed that this will evaluate to 'true'?
    std::cout << std::is_pod<A>::value << std::endl;
}
like image 752
atlaste Avatar asked Sep 27 '22 03:09

atlaste


1 Answers

In C++11 a type is deemed POD if it's

  • trivial (a scalar type, a trivially copyable class with a trivial default constructor, or array of such type/class)
  • standard layout (has no virtual functions, no virtual base classes, etc.)

Basically nothing that would hinder copying objects as if they're just constituted by raw bytes.

static_asserts are there to validate something at compile-time and doesn't change the object layout or the triviality (or the lack thereof) in constructing, copying, etc. of an object. Hence adding any number of static asserts to a type (struct/class) shouldn't change the POD-ness of it.

You can check if the compiler is considering a type as POD using std::is_pod<T>::value. This wouldn't change before and after adding static_asserts to it.

This is all that the standard says regarding static_asserts. From [dcl.dcl]:

In a static_assert-declaration the constant-expression shall be a constant expression that can be contextually converted to bool. If the value of the expression when so converted is true, the declaration has no effect. Otherwise, the program is ill-formed, and the resulting diagnostic message (1.4) shall include the text of the string-literal, except that characters not in the basic source character set (2.3) are not required to appear in the diagnostic message.

like image 88
legends2k Avatar answered Oct 06 '22 00:10

legends2k