1

Commenting and uncommenting the following statement, with significant differences in results. I am a C++ rookie, and I am very confused at this problem. I use Visual Studio 2015 Enterprise and Windows 10 64bit.

class Test
{
private:
    double d;
    float f;
    int i;
    int *pt;
    //Commenting and uncommenting this statement, with significant differences in results.
    std::shared_ptr<int> spt;
};

int main(int argc, char** argv)
{
    Test t;

    return 0;
}

When commented, the result:

         t  {d=-9.2559631349317831e+61 f=-107374176. i=-858993460 ...}  Test
         d  -9.2559631349317831e+61 double
         f  -107374176. float
         i  -858993460  int
         pt 0xcccccccc {???}    int *

When uncommented, the result:

         t  {d=0.00000000000000000 f=0.000000000 i=0 ...}   Test
         d  0.00000000000000000 double
         f  0.000000000 float
         i  0   int
         pt 0x00000000 {???}    int *
         spt    empty   std::shared_ptr<int>
fas
  • 1,393
  • 10
  • 20
Tango Xiao
  • 319
  • 3
  • 11
  • maybe because `std::shared_ptr` has a default ctor everything initializes with zeros – fas Oct 16 '19 at 02:21
  • 2
    The main problem I really see is failure to distinctly initialize the members in the first place. Unless you're shooting for a POD-type (which you don't have once you add the member `spt`). Is your deeper question whether C++ value-initializes those members of a non POD based on some part of the standard ? – WhozCraig Oct 16 '19 at 02:29
  • In my opinion, in this small program, the data members of the class should not be related to each other, and the ```spt1``` should not affect the initialization of the other members. – Tango Xiao Oct 16 '19 at 02:56
  • 1
    I had a very similar issue before, here is the question link: https://stackoverflow.com/q/55760694/9171697 – ph3rin Oct 16 '19 at 03:12
  • @TangoXiao Since you did not specify how you wanted your structure to be initialized, your opinion carries no weight (sorry). Instead, your compiler gets to decide what does and does not affect the initialization. – JaMiT Oct 16 '19 at 03:30
  • 1
    Possible duplicate of [What is a non-trivial constructor in C++?](https://stackoverflow.com/questions/3899223/what-is-a-non-trivial-constructor-in-c) – JaMiT Oct 16 '19 at 03:33

0 Answers0