Особенности языка mql5, тонкости и приёмы работы - страница 215

 

Кстати, если объвить массив   static X x[n]; и у X  Есть к-тор, то сначала  в нем все поля элементов обнулятся, даже private, и только потом вызовется к-тор. Поэтому нет никакого нарушения парадигмы ООП в том что private поля обнуляются.

А вот то, что конструктор не отрабатывал - это косяк.

 
mktr8591 #:

Кстати, если объвить массив   static X x[n]; и у X  Есть к-тор, то сначала  в нем все поля элементов обнулятся, даже private, и только потом вызовется к-тор. Поэтому нет никакого нарушения парадигмы ООП в том что private поля обнуляются.

Отлично. Получается, что обнуление идет ДО конструктора, а посему все корректно. Спасибо!

 
Igor Makanu #:

посмотрел на свои изыскания в MQL5, бывает и хуже, я даже так историю в индикаторе по нескольким ТФ подкачиваю:

в оператор for много что можно записать ))) 

Не встречал вызов void-функции в операторе for. Остальные варианты довольно часто попадаются.

 
mktr8591 #:
Забыл добавить, что если в классе есть нетривиальные поля (объекты), то после zero-init всего объекта для таких полей будет вызван их default c-tor.

Читаем:

The effects of value initialization are:

1) if  T  is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;
2) if  T  is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and the semantic constraints for default-initialization are checked, and if  T  has a non-trivial default constructor, the object is default-initialized;
3) if  T  is an array type, each element of the array is value-initialized;
4) otherwise, the object is zero-initialized.


Читаем про default-initialized:

  • if  T  is a (possibly cv-qualified) non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object;
  • if  T  is an array type, every element of the array is default-initialized;
  • otherwise, no initialization is performed: the objects with automatic storage duration (and their subobjects) contain indeterminate values.

UB!

То, что тебе компилятор инициализирует нулями, ни о чем не говорит, сегодня инициализирует, а завтра, после очередного обновления....

 
Vladimir Simakov #:

Читаем:

The effects of value initialization are:

1) if  T  is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;
2) if  T  is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and the semantic constraints for default-initialization are checked, and if  T  has a non-trivial default constructor, the object is default-initialized;
3) if  T  is an array type, each element of the array is value-initialized;
4) otherwise, the object is zero-initialized.


Читаем про default-initialized:

  • if  T  is a (possibly cv-qualified) non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object;
  • if  T  is an array type, every element of the array is default-initialized;
  • otherwise, no initialization is performed: the objects with automatic storage duration (and their subobjects) contain indeterminate values.

UB!

То, что тебе компилятор инициализирует нулями, ни о чем не говорит, сегодня инициализирует, а завтра, после очередного обновления....

Мой пост "Забыл добавить...." писался как дополнение к предыдущему посту:

Форум по трейдингу, автоматическим торговым системам и тестированию торговых стратегий

Особенности языка mql5, тонкости и приёмы работы

mktr8591, 2021.11.18 18:15

@A100




Если вспомнить, что mql порожден от C++, то там оба эти примера (их аналоги) хорошо работают, потому что в этих классах нет конструкторов (т.е. есть имплицитный конструктор):

  • Объявление ClassX x[n]={}; приводит к value-initialization каждого элемента массива.
  • Если у ClassX нет пользовательских конструкторов (но есть неудаленный конструктор по умолчанию), то производится zero-initialization объектов класса - независимо от наличия private полей.
  • Но если есть const поля, то ктор по умолчанию будет неявно удален, поэтому ошибка компилятора.

Пример в C++:

#include <iostream>
using namespace std;

class X
{
    int a;
    public:
    int get(){return a;}

    //X(){}   //так массив x не обнуляется
    //а если нет конструктора - то обнуляется
};

int main()
{
    X x[10]={};
    for (int i=0; i<10;i++)   cout<<x[i].get()<<endl;
}

Так что если в структуре /классе нет const полей, то логика работы корректная.


В нем рассматривалась определенная ситуация - когда в классе нет пользовательских конструкторов  и есть неудаленный имплицитный конструктор. В этом случае  пункт 1 процитированный вами, не подходит.

Применяется пункт  "2) if  T  is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and the semantic constraints for default-initialization are checked, and if  T  has a non-trivial default constructor, the object is default-initialized;""


Так что все сходится.

 
Vladimir Simakov #:

Читаем:

The effects of value initialization are:

1) if  T  is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;
2) if  T  is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and the semantic constraints for default-initialization are checked, and if  T  has a non-trivial default constructor, the object is default-initialized;
3) if  T  is an array type, each element of the array is value-initialized;
4) otherwise, the object is zero-initialized.


Читаем про default-initialized:

  • if  T  is a (possibly cv-qualified) non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object;
  • if  T  is an array type, every element of the array is default-initialized;
  • otherwise, no initialization is performed: the objects with automatic storage duration (and their subobjects) contain indeterminate values.

UB!

То, что тебе компилятор инициализирует нулями, ни о чем не говорит, сегодня инициализирует, а завтра, после очередного обновления....

Упс. не правильно прочитал. В этом случае:

2) if  T  is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and the semantic constraints for default-initialization are checked, and if  T  has a non-trivial default constructor, the object is default-initialized;
 
fxsaber #:

Отлично. Получается, что обнуление идет ДО конструктора, а посему все корректно. Спасибо!

На всякий случай уточню - это только для static (это все про C++). Для локальных переменных, если есть пользовательский к-тор, то обнуления нет.
 
fxsaber #:

Не встречал вызов void-функции в операторе for. Остальные варианты довольно часто попадаются.

в 3-й параметр оператора for можно записать все что душе угодно, по сути оператор for может заменить оператор if() с {.....}

ЗЫ: еще видел макросы вида

do
{
.....
}while(0)
 
Igor Makanu #:

в 3-й параметр оператора for можно записать все что душе угодно, по сути оператор for может заменить оператор if() с {.....}

ЗЫ: еще видел макросы вида

Точку с запятой убери, а то весь смысл потерялся)))

 
Vladimir Simakov #:

Точку с запятой убери, а то весь смысл потерялся)))

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

Причина обращения: