Модераторы: LSD

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> C++ - его сила и его слабости, обсудить 
:(
    Опции темы
Sartorius
Дата 9.2.2007, 21:40 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1568
Регистрация: 18.7.2006
Где: Ivory tower

Репутация: нет
Всего: 37



 Мнда. Многовато чего-то регистров. А ведь еще и результаты промежуточные где то хранить нада....
PM MAIL ICQ   Вверх
MAKCim
Дата 9.2.2007, 21:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Воін дZэна
****


Профиль
Группа: Экс. модератор
Сообщений: 5644
Регистрация: 10.12.2005
Где: Менск, РБ

Репутация: 8
Всего: 207



Цитата(Любитель @  9.2.2007,  21:02 Найти цитируемый пост)
Но ведь с инлайн именно так часто получается. Или register-переменные (которыми никто не пользуется  smile ) -  боюсь, что компилер не обратит внимание на ваше требование

всегда есть
Код

__attribute__((always_inline))

и
Код

register int a __asm__("eax") = 7;

для таких случаев

Добавлено @ 21:48 
Цитата(Sartorius @  9.2.2007,  21:40 Найти цитируемый пост)
Мнда. Многовато чего-то регистров. А ведь еще и результаты промежуточные где то хранить нада....

так 2 регистра еще есть  smile (в худшем случае)


Это сообщение отредактировал(а) MAKCim - 9.2.2007, 21:48


--------------------
Ах, у елі, ах, у ёлкі, ах, у елі злыя волкі ©

PM MAIL   Вверх
Любитель
Дата 9.2.2007, 22:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Программист-романтик
****


Профиль
Группа: Комодератор
Сообщений: 3645
Регистрация: 21.5.2005
Где: Воронеж

Репутация: 5
Всего: 92



MAKCim, я, конечно понимаю твои взгляды, но не надо всё же равнять gcc и стандартные плюсы  smile


--------------------
PM MAIL ICQ Skype   Вверх
MAKCim
Дата 9.2.2007, 23:08 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Воін дZэна
****


Профиль
Группа: Экс. модератор
Сообщений: 5644
Регистрация: 10.12.2005
Где: Менск, РБ

Репутация: 8
Всего: 207



Цитата(Любитель @  9.2.2007,  22:46 Найти цитируемый пост)
MAKCim, я, конечно понимаю твои взгляды, но не надо всё же равнять gcc и стандартные плюсы

нет, подожди
В С++ по стандарту inline функция - есть подстановочная функция, а register переменные - переменные в регистрах
т. е любой компилятор номинально обязан все inline функции подставлять непосредственно (благо ограничений в отличие от register переменных нет) и располагать register переменные в регистрах за исключением ситуации, когда отсутствуют свободные регистров, а заниматься оптимизацией должен при включенной оптимизации
т. е я хочу сказать, что в обычном режиме он должен тупо следовать спецификации языка, а со включенной оптимизацией - заниматься эвристикой и прочим шаманством

Это сообщение отредактировал(а) MAKCim - 9.2.2007, 23:14


--------------------
Ах, у елі, ах, у ёлкі, ах, у елі злыя волкі ©

PM MAIL   Вверх
Void
Дата 9.2.2007, 23:41 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


λcat.lolcat
****


Профиль
Группа: Участник Клуба
Сообщений: 2206
Регистрация: 16.11.2004
Где: Zürich

Репутация: 11
Всего: 173



MAKCim
7.1.2/2
Цитата
The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; [...]

Между предпочтением и обязательством есть разница.

Добавлено @ 23:42 
7.1.1/3
Цитата
A register specifier has the same semantics as an auto specifier together with a hint to the implementation that the object so declared will be heavily used. [Note: the hint can be ignored and in most implementations it will be ignored if the address of the object is taken. —end note]



--------------------
“Coming back to where you started is not the same as never leaving.” — Terry Pratchett
PM MAIL WWW GTalk   Вверх
Любитель
Дата 10.2.2007, 00:45 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Программист-романтик
****


Профиль
Группа: Комодератор
Сообщений: 3645
Регистрация: 21.5.2005
Где: Воронеж

Репутация: 5
Всего: 92



Что бегло нашёл по restrict:
Код

The intended use of the restrict qualifier (like the register storage class) is to promote optimization


Добавлено @ 00:45 
MAKCim, кстати выше я говорил про __atribute__ и __asm__.


--------------------
PM MAIL ICQ Skype   Вверх
SergeCpp
Дата 10.2.2007, 01:09 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


 
**


Профиль
Группа: Участник
Сообщений: 955
Регистрация: 8.8.2005
Где: At Home

Репутация: 3
Всего: 124



Вот выдержки из довольно старой статьи Денниса Ритчи (1988, noalias comments to X3J11)
Цитата
      `Noalias' is much more dangerous; the committee is planting timebombs that are sure to explode in people's faces.  Assigning an ordinary pointer to a pointer to a `noalias' object is a license for the compiler to undertake aggressive optimizations that are completely legal by the committee's rules, but make hash of apparently safe programs.  Again, the problem is most visible in the library; parameters declared `noalias type *' are especially problematical. 

      In order to write such a library routine using the new parameter declarations, it is in practice necessary to violate 3.3.4: `A pointer to a noalias-qualified type ... may be converted to ... the non-noalias-qualified type.  If the pointed to object is referred to by means of the converted pointer, the behavior is undefined.' Thus, the problem that occurs with `const' is now much worse; there are no interesting and legal uses of strchr. 

      How do you code a routine whose prototype specifies a noalias pointer?  If you fail to violate 3.3.4, but instead try to rewrite the declarations of temporary variables to make them agree in type with parameters, it becomes hard to be sure that the routine works.  Consider the specification of strtok: 

    char *strtok(noalias char *s1, noalias const char *s2);

It retains a static pointer to its writable, `noalias' first argument.  Can you be sure that this routine can be made safe under the rules?  I have studied it, and the answer is conditionally yes, provided one accepts certain parts of the Standard as gospel (for example that `noalias' handles will not be synchronized at certain times) while ignoring other parts.  It is a very dodgy thing.  For other routines, it is certain that complete rewriting is necessary: qsort,  for example, is full of pointers that rove the argument array and change it here and there.  If these local pointers are qualified with `noalias,' they may all be pointing to different virtual copies of parts of the array; in any event, the argument itself may have a virtual object that might be completely untouched by the attempt to sort it. 
      The `noalias' rules have the assignment and cast restrictions backwards.  Assigning a plain pointer to a const-qualified pointer (pc = p) is well-defined by the rules and is safe, in that it restricts what you can do with pc.  The other way around (p = pc) is forbidden, presumably because it creates a writable access path to an unwritable object. With `noalias,' the rules are the same (pna = p is OK, p = pna is forbidden), but the realistic safety requirements are completely different.  Both of these assignments are equally suspicious, in that both create two access paths to an object, one manifestation of which might be virtual. 

      Here is another way of observing the asymmetry: the presence of `const type *' in a parameter list is a useful piece of interface information, but `noalias type *' most assuredly is not.  Given the declaration 

    memcpy(noalias void *s1, const noalias void *s2, size_t n);

what information can one glean from it?  Some committee members apparently believe that it conveys either to the reader or to the compiler that the routine is safe, provided that the strings do not overlap.  They are mistaken. Perhaps the committee's intent is not reflected in the current words of the Standard, but I can find nothing there that justifies their belief.  The rules (page 65, lines 19-20) specify `all objects accessible by these [noalias] lvalues,' which is the entirety of both array arguments. 
      More generally, suppose I see a prototype 

    char *magicfunction(noalias char *, noalias char *);

Is there anything at all I can conclude about the requirements of magicfunction?  Is there anything at all I can conclude about things it promises to do or not to do?  All I learn from the Rationale (page 52) is that such a routine enjoins me from letting the arguments overlap, but this is at variance with the Standard, which gives a stronger injunction. 
      Within the function itself, things are equally bad.  A `const type *' parameter, though it presents problems for strchr and other routines, does usefully constrain the function: it's not allowed to store through the pointer.  However, within a function with a `noalias type *' parameter, nothing is gained except bizarre restrictions: it can't cast the parameter to a plain pointer, and it can't assign the parameter to another noalias pointer without creating unwanted handles and potential virtual objects.  The interface must say noalias, or at any rate does say noalias, so the author of the routine has all the grotesque inventions of 3.5.3 (handles, virtual objects) rubbed in his face, like or not. 

      The utter wrongness of `noalias' is that the information it seeks to convey is not a property of an object at all. `Const,' for all its technical faults, is at least a genuine property of objects; `noalias' is not, and the committee's confused attempt to improve optimization by pinning a new qualifier on objects spoils the language. `Noalias' is a bogus invention that is not necessary, and not in any case sufficient for its apparent purpose. 

      Earlier languages flirted with gizmos intended to help optimization, and generally abandoned them.  The original Fortran, for example, had a FREQUENCY statement that didn't help much, confused people, and was dropped.  PL/1 had `normal/abnormal' and `uses/sets' attributes that suffered a similar fate.  Today, these are generally looked on as adolescent experiments. 

      On the other hand, the insufficiency of `noalias' is suggested by Cray's Fortran compiler, which has 20 separate keywords that control various details of optimization.  They are specified by an equivalent of #pragma,  and thus, despite their oddness, can be ignored when trying to understand the meaning of a program. 

      Perhaps there is some reason to provide a mechanism for asserting, in a particular patch of code, that the compiler is free to make optimistic assumptions about the kinds of aliasing that can occur.  I don't know any acceptable way of changing the language specification to express the possibility of this kind of optimization, and I don't know how much performance improvement is likely to result.  I would encourage compiler-writers to experiment with extensions, by #pragma or otherwise, to see what ideas and improvements they can come up with, but I am certain that nothing resembling the noalias proposal should be in the Standard.

Цитата
      Noalias must go.  This is non-negotiable. 

      It must not be reworded, reformulated or reinvented.  The draft's description is badly flawed, but that is not the problem.  The concept is wrong from start to finish.  It negates every brave promise X3J11 ever made about codifying existing practices, preserving the existing body of code, and keeping (dare I say it?) `the spirit of C.'



Это сообщение отредактировал(а) SergeCpp - 10.2.2007, 01:12
PM MAIL WWW ICQ   Вверх
SergeCpp
Дата 10.2.2007, 09:18 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


 
**


Профиль
Группа: Участник
Сообщений: 955
Регистрация: 8.8.2005
Где: At Home

Репутация: 3
Всего: 124



Цикл статей Страуструпа о совместимости C и C++

Sibling rivalry: C and C++. AT&T Labs — Research Technical Report. January 2002

C and C++: Siblings. The C/C++ Users Journal. July 2002
C and C++: A Case for Compatibility. The C/C++ Users Journal. August 2002
C and C++: Case Studies in Compatibility. The C/C++ Users Journal. September 2002

Положение дел

David R. Tribble. Incompatibilities Between ISO C and ISO C++

PM MAIL WWW ICQ   Вверх
MAKCim
Дата 10.2.2007, 10:29 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Воін дZэна
****


Профиль
Группа: Экс. модератор
Сообщений: 5644
Регистрация: 10.12.2005
Где: Менск, РБ

Репутация: 8
Всего: 207



Цитата(Void @  9.2.2007,  23:41 Найти цитируемый пост)
Между предпочтением и обязательством есть разница.

но фактически ограничений на сегодня использоанию inline нет, и так как
Цитата

is to be preferred to the usual function call mechanism

то логично было бы в обычном (не оптимизирующем) режиме всегда использовать inline, если это явно указано
тогда бы программист был уверен, как именно будет в итоге выглядеть код
Цитата(Любитель @  10.2.2007,  00:45 Найти цитируемый пост)
MAKCim, кстати выше я говорил про __atribute__ и __asm__. 

я понял



--------------------
Ах, у елі, ах, у ёлкі, ах, у елі злыя волкі ©

PM MAIL   Вверх
mr666
Дата 11.2.2007, 17:22 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 42
Регистрация: 28.3.2006

Репутация: нет
Всего: нет



Вроде современные компиляторы игнорируют register переменные... анализируя код ..
PM MAIL   Вверх
Любитель
Дата 11.2.2007, 19:29 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Программист-романтик
****


Профиль
Группа: Комодератор
Сообщений: 3645
Регистрация: 21.5.2005
Где: Воронеж

Репутация: 5
Всего: 92



MAKCim, ну всё же, если компилер будет просто игнорировать инлайн, формально он удовлетворяет стандарту. К тому же не всегда встраивание возможно. Например, имеем рекурсивную функцию (в тривиальный цикл не разворачиваемую - только с использованием стека). Компилер не сможет её заинлайнить. Да и в жебаге мне кажется любую рекурсивную функцию он встраивать не будет. Игнор инлайна гораздо проще, чем развёртывание рекурсии (даже в цикл).

То же имеем и с регистер, и с рестрикт.


--------------------
PM MAIL ICQ Skype   Вверх
MAKCim
Дата 11.2.2007, 21:43 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Воін дZэна
****


Профиль
Группа: Экс. модератор
Сообщений: 5644
Регистрация: 10.12.2005
Где: Менск, РБ

Репутация: 8
Всего: 207



Цитата(Любитель @  11.2.2007,  19:29 Найти цитируемый пост)
Например, имеем рекурсивную функцию (в тривиальный цикл не разворачиваемую - только с использованием стека). Компилер не сможет её заинлайнить

да как нефиг
пусть есть
Код

static inline void recurse(int N) {
    recurse(N + 1);
}

int main() {
    recurse(0);
    return 0;
}

функция
Код

recurse:
    push ebp
    mov ebp, esp
    sub esp, 4
    mov eax, [ebp + 8]
    mov [ebp - 4], eax
    call recurse
...
main:
    push 0
    call recurse
...

inline
Код

main:
    push 0
    push offset @1
recurse:
    sub esp, 4
    mov eax, [esp + 4]
    mov [esp], eax
    call recurse
@1:
...



--------------------
Ах, у елі, ах, у ёлкі, ах, у елі злыя волкі ©

PM MAIL   Вверх
Любитель
Дата 11.2.2007, 21:50 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Программист-романтик
****


Профиль
Группа: Комодератор
Сообщений: 3645
Регистрация: 21.5.2005
Где: Воронеж

Репутация: 5
Всего: 92



Цитата(Любитель @  11.2.2007,  19:29 Найти цитируемый пост)
в тривиальный цикл не разворачиваемую

 smile Только что писал про tail recursion в Nemerle.

А вообще оффтопик почуть пошёл.


--------------------
PM MAIL ICQ Skype   Вверх
unicuum
Дата 15.3.2007, 04:53 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 830
Регистрация: 16.3.2005
Где: Рашка

Репутация: 1
Всего: 8



Как утверждает создатель С++ Бьерн Страуструп в его третьем издании книги «Язык программирования С++» - «не важно на каком языке программируешь, важно что из себя представляешь ты сам». И я с ним полностью согласен.


--------------------
user posted image
обычный день на винграде
PM   Вверх
esperant0
Дата 15.3.2007, 15:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 714
Регистрация: 20.5.2005

Репутация: нет
Всего: 14



Цитата(unicuum @ 15.3.2007,  04:53)
Как утверждает создатель С++ Бьерн Страуструп в его третьем издании книги «Язык программирования С++» - «не важно на каком языке программируешь, важно что из себя представляешь ты сам». И я с ним полностью согласен.

Это еще Тьюринг доказал. А Страуструп всего лишь процитировал в вольной форме.


--------------------
 
 Student->Teacher Assistant ->Research assistant->Microsoft Software Development Engineer 

Пользователь получил наказание за то, что проигнорировал замечание которое было написано модератором  а затем стерто и которое он - пользователь не мог видеть. 
PM MAIL   Вверх
Ответ в темуСоздание новой темы Создание опроса
Правила ведения Религиозных войн
Smartov
1. Уважайте собеседника
2. Собеседник != враг
3. Старайтесь воздерживаться от тем вида "Windows Rulez" или "Linux Rulez"

С уважением, Smartov.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Религиозные войны | Следующая тема »


 




[ Время генерации скрипта: 0.0905 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.