Initializing an erroneous array instead of initializing the instance copy constructor

#include<iostream> using namespace std; class Test { public: Test(){} Test(int param):i(param){} int i; }; int main() { Test obj1(100); //Test obj2[100](obj1) ; - This doesn't work I know Test obj3[10] = obj1; //This works cout<<obj3[9].i<<endl; return 1; } 

In the above code, Test obj2[100](obj1); does not work, but Test obj3[10] = obj1;

Why the former is supported, but the latter. (Both will call the copy constructor.)

Is it that the former is not supported due to implementation restrictions in compilers?

Edit: I am not using C ++ 11. gcc version 4.8.2 (i686-posix-dwarf-rev3, built by the MinGW-W64 project) Qt 5.3.1

Any conclusion?

+5
source share
1 answer

I mainly answer your last comment because all the elements have already been indicated in the comments.

What we can see:

  • first syntax Test obj2[100](obj1); rejected as an error of all tested compilers, because ... it does not meet the C ++ language specification!
  • Second syntax Test obj2[100] = obj1; does not seem to meet current specifications because you are initializing the array with a single element. More on this:
    • clang (and MSVC) will encounter it: they need curly braces, and then only the first element is initialized (will be: Test obj2[100] = {obj1}; )
    • gcc (4.5 - 4.9) takes it and initializes all elements of the array with a copy of obj1

My opinion is that since it is not clear that this is the correct C ++, and since it causes errors on some heavily used C ++ compilers, you should avoid using even the second syntax unless it is documented in a red blinking font.

+1
source

Source: https://habr.com/ru/post/1210550/


All Articles