0

Question1:

struct S
{
   size_t size;
   int j;
   int k;
   int l;
};

S s={sizeof(S)};

Doest C++ standard say,the above {} will initialize "j,k,l" to 0? Seems it will do, is it part of cpp standard?

Question2:

int main()
{
    int* pi=new int[5];
    for(int i=0;i<5;++i)
        cout<<pi[i]<<',';
    return 0;
}

Here the elements in pointer to array(pi) are not initialized, my running result may look like

6785200,6782912,0,0,0,

But if I change it to

int main()
{
    int* pi=new int[5]();//use ()
    for(int i=0;i<5;++i)
        cout<<pi[i]<<',';
    return 0;
}

Then, all pi elements are "0". Seems "()" will give elements a "0" value. Is this part of cpp standard?

I also tried to give another value using "()" like this:

int* pi=new int[5](7);

But it fails compilation. How could I give initialization values to an pointer to array with all elements having same value?

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
Troskyvs
  • 7,537
  • 7
  • 47
  • 115

2 Answers2

2

Question 1

Yes, it is guarantied by aggregate initialization in particular:

If the number of initializer clauses is less than the number of members [and bases (since C++17)] or initializer list is completely empty, the remaining members [and bases (since C++17)] are initialized [by their default initializers, if provided in the class definition, and otherwise (since C++14)] by empty lists, which performs value-initialization. If a member of a reference type is one of these remaining members, the program is ill-formed (references cannot be value-initialized).

.

Question 2

Use std::vector:

std::vector<int> pi(5, 7);
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • I think you need to reproduce the rev boxes somehow or tweak the quote a bit. Without the boxes it's hard to tell what the "(since C++1X)" appertains to. – T.C. Jun 08 '16 at 02:50
2

There is a perfect answer to question 1 already, I will answer question 2.

Yes, your observation is correct. Adding () after the new turns default initialization of the elements into value initialization. The first form does nothing with created objects (so you observe random numbers), but the value initialization will initialize members - and in this case, will set elements to 0. Unfortunately, there is no way to perform a specific initialization for dynamic int arrays - you can either leave them uninititalized or value-initialize them (to 0).

Using std::vector solves this problem.

SergeyA
  • 61,605
  • 5
  • 78
  • 137