Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Общие вопросы > throw как выход из рекурсии???


Автор: Irdis 4.4.2010, 21:45
При поиске элемента в дереве, советуют сделать следующее.
Кидать эксепшн, если нашли элемент; и отлавливать его. Мотивировалось это тем, что это эффективный выход из рекурсии.
Это нормально? 

ИМХО. 
Эксепшн - это эксепшн, которые следует использовать с той целью с которой их создавали. 
Написал мощный return, если нашли элемент. 

Автор: GoldFinch 4.4.2010, 21:53
в С++ считается, что эксепшн надо создавать при исключительной ситуации. 
нахождение элемента - это не исключительная ситуация.

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

Автор: jonie 4.4.2010, 22:44
а вот гугловские ребята вообще запрещают использовать эксепшены..... а насчет "эффективности" - можно и поспорить..

Автор: GoldFinch 4.4.2010, 23:20
каждый извращается как может %)
можно и классы в С++ запретить

Добавлено через 1 минуту и 21 секунду
"эффективный" - это конечно не в плане быстродействия, а в плане удобства написания кода

Автор: boostcoder 5.4.2010, 00:18
Цитата(jonie @  4.4.2010,  22:44 Найти цитируемый пост)
а вот гугловские ребята вообще запрещают использовать эксепшены

как аргументируют?

Автор: jonie 5.4.2010, 08:32
boostcoder, просто: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Exceptions

Автор: boostcoder 5.4.2010, 09:28
исчерпывающе. вопросов не осталось, ни одного smile

Автор: azesmcar 5.4.2010, 10:02
Цитата(jonie @  5.4.2010,  08:32 Найти цитируемый пост)
boostcoder, просто: http://google-styleguide.googlecode.com/sv....xml#Exceptions

там внизу кнопочка есть
Цитата

    *  Exceptions allow higher levels of an application to decide how to handle "can't happen" failures in deeply nested functions, without the obscuring and error-prone bookkeeping of error codes.

    * Exceptions are used by most other modern languages. Using them in C++ would make it more consistent with Python, Java, and the C++ that others are familiar with.

    * Some third-party C++ libraries use exceptions, and turning them off internally makes it harder to integrate with those libraries.
    * Exceptions are the only way for a constructor to fail. We can simulate this with a factory function or an Init() method, but these require heap allocation or a new "invalid" state, respectively.

    * Exceptions are really handy in testing frameworks.

Cons:
    * When you add a throw statement to an existing function, you must examine all of its transitive callers. Either they must make at least the basic exception safety guarantee, or they must never catch the exception and be happy with the program terminating as a result. For instance, if f() calls g() calls h(), and h throws an exception that f catches, g has to be careful or it may not clean up properly.

    * More generally, exceptions make the control flow of programs difficult to evaluate by looking at code: functions may return in places you don't expect. This results maintainability and debugging difficulties. You can minimize this cost via some rules on how and where exceptions can be used, but at the cost of more that a developer needs to know and understand.

    * Exception safety requires both RAII and different coding practices. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid requiring readers to understand the entire call graph, exception-safe code must isolate logic that writes to persistent state into a "commit" phase. This will have both benefits and costs (perhaps where you're forced to obfuscate code to isolate the commit). Allowing exceptions would force us to always pay those costs even when they're not worth it.

    * Turning on exceptions adds data to each binary produced, increasing compile time (probably slightly) and possibly increasing address space pressure.

    * The availability of exceptions may encourage developers to throw them when they are not appropriate or recover from them when it's not safe to do so. For example, invalid user input should not cause exceptions to be thrown. We would need to make the style guide even longer to document these restrictions!

Decision:

On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions.

Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in in a new project. The conversion process would be slow and error-prone. We don't believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden.

Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch.

There is an exception to this rule (no pun intended) for Windows code.

Автор: boostcoder 5.4.2010, 10:20
azesmcar, недодумался smile 

Автор: azesmcar 5.4.2010, 10:31
Цитата(boostcoder @  5.4.2010,  10:20 Найти цитируемый пост)
azesmcar, недодумался smile 

Я тоже сперва не додумался, потом прочел наверху smile 

не нашел ни одного серьезного аргумента, особенно мне понравился этот

Цитата(azesmcar @  5.4.2010,  10:02 Найти цитируемый пост)

    * The availability of exceptions may encourage developers to throw them when they are not appropriate or recover from them when it's not safe to do so.


Цитата(azesmcar @  5.4.2010,  10:02 Найти цитируемый пост)
We would need to make the style guide even longer to document these restrictions!

даааа, это конечно серьезная причина smile 

ребята видимо не понимают для чего нужен документ, описывающий стиль. Они хотят уместить в нем все советы Майерса и Саттера.

Автор: boostcoder 5.4.2010, 10:40
и вправду, странная аргументация.
а вообще, что-то многовато этих стайл-гайдов поразводилось. у каждой конторы по одному минимум.

Автор: Alek86 11.4.2010, 20:06
оффтоп
azesmcar, ага, тупые америкосы smile

Автор: azesmcar 11.4.2010, 20:11
Цитата(Alek86 @  11.4.2010,  20:06 Найти цитируемый пост)
оффтоп
azesmcar, ага, тупые америкосы smile

я их не считаю тупыми smile 

Автор: boostcoder 11.4.2010, 20:56
Цитата(Alek86 @  11.4.2010,  20:06 Найти цитируемый пост)
ага, тупые америкосы

как понимать?

Автор: Alek86 11.4.2010, 21:11
Цитата(boostcoder @  11.4.2010,  20:56 Найти цитируемый пост)
как понимать?

это ответ на
Цитата(azesmcar @  5.4.2010,  10:31 Найти цитируемый пост)
ребята видимо не понимают для чего нужен документ, описывающий стиль


ЗЫ.  ироничный

Автор: azesmcar 11.4.2010, 21:41
Цитата(Alek86 @  11.4.2010,  21:11 Найти цитируемый пост)
ЗЫ.  ироничный 

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

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)