Преимущества списков Инициализации

Я ответил на свой собственный вопрос. Я просто должен был играть со свойствами высоты диалогового окна и некоторые элементы в диалоговом окне. Хороший звонят мне!

40
задан Ankur 21 October 2009 в 06:00
поделиться

4 ответа

The second version is calling string's default ctor and then string's copy-assignment operator -- there could definitely be (minor) efficiency losses compared to the first one, which directly calls c's copy-ctor (e.g., depending on string's implementation, there might be useless allocation-then-release of some tiny structure). Why not just always use the right way?-)

33
ответ дан 27 November 2019 в 01:36
поделиться

Я думаю, что единственный способ инициализировать константные элементы данных - это список инициализации

Например. в заголовке:

class C
{
    C();
private:
    const int x;
    int y;
}

И в файле cpp:

C::C() :
    x( 10 ),
    y( 10 )
{
    x = 20; // fails
    y = 20;
}
15
ответ дан 27 November 2019 в 01:36
поделиться

Remember that there is a distinct difference between a copy constructor and an assignment operator:

  • the copy ctor constructs a new object using some other instance as a place to get initialization information from.
  • the assignment operator modifies an already existing object that has already been fully constructed (even if it's only by using a default constructor)

So in your second example, some work has already been done to create name by the time that

 name=n;

is reached.

However, it's quite possible (especially in this simple example) that the work done is vanishingly small (probably just zeroing out some data members in the string object) and that the work is optimized away altogether in an optimized build. but it's still considered good form to use initializer lists whenever possible.

11
ответ дан 27 November 2019 в 01:36
поделиться

Это отличный способ инициализировать члены, которые:

  • являются константными
  • не имеют конструктора по умолчанию (он частный)
13
ответ дан 27 November 2019 в 01:36
поделиться
Другие вопросы по тегам:

Похожие вопросы: