dimanche 22 mars 2020

g++ compiler issue with aligned_storage - Is this a compiler bug?

I copied a program below from this link

#include <iostream>
#include <type_traits>

struct A {  // non-POD type
  int avg;
  A (int a, int b) : avg((a+b)/2) {}
};

typedef std::aligned_storage<sizeof(A),alignof(A)>::type A_pod;

int main() {
  A_pod a,b;
  new (&a) A (10,20);
  b=a;
  std::cout << reinterpret_cast<A&>(b).avg << std::endl;

  return 0;
}

I ran gdb on this code to understand the size of various constituents and the results are as below:

(gdb) b 18
Breakpoint 1 at 0x96d: /home/ripunjay/study/bitbucket/study/cpp/aligned_storage.cpp:18. (3 locations)
(gdb) r
Starting program: /home/ripunjay/study/bitbucket/study/cpp/aligned_storage 

Breakpoint 1, _GLOBAL__sub_I_main () at aligned_storage.cpp:18
18  }
(gdb) ptype a
type = const union {
    int i[2];
    double d;
}
(gdb) ptype A_pod
type = union std::aligned_storage<4, 4>::type {
    unsigned char __data[4];
    struct {
        <no data fields>
    } __align;
}
(gdb) ptype A_
No symbol "A_" in current context.
(gdb) ptype A
type = struct A {
    int avg;
  public:
    A(int, int);
}
(gdb) p sizeof(A)
$1 = 4
(gdb) p sizeof(a)
$2 = 8
(gdb) p sizeof(b)
$3 = 8

(gdb) ptype A
type = struct A {
    int avg;
  public:
    A(int, int);
}

Later on to see a normal constructor call I added a single line in main() to construct an object c as follows -

int main() {
  A_pod a,b;
  A c(10,20);
  new (&a) A (10,20);
  b=a;
  std::cout << reinterpret_cast<A&>(b).avg << std::endl;

  return 0;
}

This caused the sizes and even type definitions for a and b to change. It was quite surprising that even if this newly added line is commented out the compiler has different behaviour.

(gdb) r
Starting program: /home/ripunjay/study/bitbucket/study/cpp/aligned_storage 
15

Breakpoint 1, main () at aligned_storage.cpp:18
18    return 0;
(gdb) ptype a
type = union std::aligned_storage<4, 4>::type {
    unsigned char __data[4];
    struct {
        <no data fields>
    } __align;
}
(gdb) ptype b
type = union std::aligned_storage<4, 4>::type {
    unsigned char __data[4];
    struct {
        <no data fields>
    } __align;
}
(gdb) ptype A_pod
type = union std::aligned_storage<4, 4>::type {
    unsigned char __data[4];
    struct {
        <no data fields>
    } __align;
}


g++ --version 
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 Copyright (C) 2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions.  There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Aucun commentaire:

Enregistrer un commentaire