https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94303

            Bug ID: 94303
           Summary: Program result error When using global object array
                    (partially initialized with a special constructor, and
                    the rest with the default constructor)
           Product: gcc
           Version: 8.3.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: moonchasing1999 at gmail dot com
  Target Milestone: ---

g++ version: 8.3.0 (and later)
system: Ubuntu 18.04
complete command line that triggers the bug: g++ -std=c++11 -o out main.cpp
compiler output: none
-----------------------

When I use g++8.3 and later version to compile and run the following code, the
results are not as expected. But if I use 8.2 and earlier version or other
compiler, like clang, wont't occure a fault result.

/* class define */
class A
{
private:
    int d = 9;
public:
    A()=default;
    A(int a) : d(a) {}
    void f() {cout << d << endl;}
};
/* class define end */

/* test code 1 */
A a[3] = {1}; //global
int main()
{
    a[0].f();  //Output: 1
    a[1].f();  //Output: 9
    a[2].f();  //Output: 0  //error
    return 0;
}
/* test code 1 end */

But if put A a[3] = {1} in main() function, it doesn't error.
/* test code 2 */

int main()
{
    A a[3] = {1};
    a[0].f();  //Output: 1
    a[1].f();  //Output: 9
    a[2].f();  //Output: 9  //right!
    return 0;
}
/* test code 2 end */

And I find add number in initialization list, how many elements are initialized
then the last number of elements in the array is an incorrect result. For
example:

/* test code 3 */
A a[100]={1,1, 1};  // global

int main()
{
    a[0].f();   //Output: 1
    a[1].f();   //Output: 1
    a[2].f();   //Output: 1
    a[3].f();   //Output: 9
    a[4].f();   //Output: 9
    .....       //Output: 9
    a[96].f();  //Output: 9
    a[97].f();  //Output: 0  //error
    a[98].f();  //Output: 0  //error
    a[99].f();  //Output: 0  //error
    return 0;
}
/* test code 3 end */

/* full code of test code 1 */
class A
{
private:
    int d = 9;
public:
    A()=default;
    A(int a) : d(a) {}
    void f() {cout << d << endl;}
};

A a[3]={1};

int main()
{
    a[0].f();
    a[1].f();
    a[2].f();
    return 0;
}
/* full code end*/

Reply via email to