Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have some questions about the way to assign values to the std::array

Tags:

c++

c++11

c++14

I'm learning C++ on codesdope.com and I have read a document on another website, learncpp.com. But these two websites have different ways to assign values ​​to the array.

//codesdope.com

std::array<int,5> n  {{1,2,3,4,5}};
//learncpp.com

std::array<int,5> n = {1,2,3,4,5};

Which way is more accurate? Which way should I choose? What is the difference between them?

like image 835
Quốc Cường Avatar asked Jun 01 '19 17:06

Quốc Cường


2 Answers

Double-braces required in C++11 prior to the CWG 1270 (not needed in C++11 after the revision and in C++14 and beyond):

// construction uses aggregate initialization
std::array<int, 5> a{ {1, 2, 3, 4, 5} }; // double-braces required in C++11 prior to the CWG 1270 revision
std::array<int, 5> a{1, 2, 3, 4, 5}; // not needed in C++11 after the revision and in C++14 and beyond
std::array<int, 5> a = {1, 2, 3, 4, 5};  // never required after =

std::array reference

like image 117
Amit G. Avatar answered Sep 28 '22 08:09

Amit G.


Both versions have the same assembly code:

    std::array<int,5> n {{1,2,3,4,5}};

    mov     rcx, qword ptr [.L__const.main.n]
    mov     qword ptr [rbp - 24], rcx
    mov     rcx, qword ptr [.L__const.main.n+8]
    mov     qword ptr [rbp - 16], rcx
    mov     edx, dword ptr [.L__const.main.n+16]
    mov     dword ptr [rbp - 8], edx

the second style:

    std::array<int,5> n2 {1,2,3,4,5};

    mov     rcx, qword ptr [.L__const.main.n2]
    mov     qword ptr [rbp - 24], rcx
    mov     rcx, qword ptr [.L__const.main.n2+8]
    mov     qword ptr [rbp - 16], rcx
    mov     edx, dword ptr [.L__const.main.n2+16]
    mov     dword ptr [rbp - 8], edx

meaning they both have the same performance. The second is better, because it is more readable.

like image 36
Oblivion Avatar answered Sep 28 '22 06:09

Oblivion