why is_standard_layout gives true here?

Viewed 67

my understanding is that not having any virtual method is one of requirements for standard layout. however, following code prints out true while there is a virtual method in struct Cancel.

if I remove the virtual method. is_stand_layout returns false which makes sense, as Cancel has members with different access control.

I tested this on gcc 10.2, 9.2 9.3 and clang 11.0, the results are the same.

is this a bug? or is there something I am missing about standard layout?

#include <variant>
#include <iostream>

struct NewOrder
{
    int i;
};
struct Cancel
{
    virtual ~Cancel() {}
    int j;
private:
    int i;
}; 
int main() {
  std::cout << std::is_standard_layout_v<std::variant<NewOrder, Cancel>> << std::endl;
  return 0;
}
1 Answers

is this a bug?

No.

is there something I am missing

You're outputting std::is_standard_layout_v<std::variant<NewOrder, Cancel>> which determines whether std::variant<NewOrder, Cancel> is standard layout rather than whether Cancel is standard layout.

why is_standard_layout gives true here?

Whether std::variant<NewOrder, Cancel> is standard layout or not doesn't necessarily depend on whether the template type arguments are themselves standard layout. The standard doesn't specify whether std::variant is or isn't standard layout. The output that you see is a side-effect of how std::variant was implemented in the standard library that you used.

Related