Padrões de desenvolvimento em C++

2 respostas
E

Olá,

Alguém tem alguma indicação de tutorial ou e-book que ensine alguns padrões de código c++ básicos?
Estou iniciando alguns projetos e apesar de serem simples e pequenos gostaria de deixá-los num padrão bacana.

Pooor exemplo, uma dúvida que me acompanha há alguns dias:
Tenho o arquivo a.cpp. Devo declarar os includes:

#include <stdio.h>
#include <stdlib.h>

em a.cpp ou no arquivo de cabeçalho a.h?

Obrigado desde já!
:smiley:

2 Respostas

ViniGodoy

Eu recomendo que você compre o livro “Effective C++” e o livro “More Effective C++”.
Similar a esses existe os livros “Exception C++” e “More Effective C++” (mas se comprar o Effective, não compre esses e vice-versa).

O effective existe na versão e-book, mas não é gratuito. Ambos dão dicas preciosas de como codificar corretamente em C++.

Abaixo, segue a lista completa das dicas. No livro, cada uma delas é explicada em detalhes, com exemplos.

Se quiser se perfeiçoar em C++, dê uma olhada no meu roadmap:
Ponto V! - Roadmap C++

Shifting From C to C++.
? Prefer const and inline to #define.
? Prefer iostream to stdio.h.
? Prefer new and delete to malloc and free.
? Prefer C++­style comments.

Memory Management.
? Use the same form in corresponding uses of new and delete.
? Use delete on pointer members in destructors.
? Be prepared for out­of­memory conditions.
? Adhere to convention when writing operator new and operator delete.
? Avoid hiding the ?normal? form of new.
? Write operator delete if you write operator new.

Constructors, Destructors, and Assignment Operators.
? Declare a copy constructor and an assignment operator for classes with dynamically allocated memory.
? Prefer initialization to assignment in constructors.
? List members in an initialization list in the order in which they are declared.
? Make destructors virtual in base classes.
? Have operator= return a reference to *this.
? Assign to all data members in operator=.
? Check for assignment to self in operator=.

Classes and Functions: Design and Declaration.
? Strive for class interfaces that are complete and minimal.
? Differentiate among member functions, non­member functions, and friend functions.
? Avoid data members in the public interface.
? Use const whenever possible.
? Prefer pass­by­reference to pass­by­value.
? Don? t try to return a reference when you must return an object.
? Choose carefully between function overloading and parameter defaulting.
? Avoid overloading on a pointer and a numerical type.
? Guard against potential ambiguity.
? Explicitly disallow use of implicitly generated member functions you don?t want.
? Partition the global namespace.

Classes and Functions: Implementation.
? Avoid returning ?handles? to internal data.
? Avoid member functions that return non­const pointers or references to members less accessible than themselves.
? Never return a reference to a local object or to a dereferenced pointer nitialized by new within the function.
? Postpone variable definitions as long as possible.
? Use inlining judiciously.
? Minimize compilation dependencies between files.

Inheritance and Object­Oriented Design.
? Make sure public inheritance models ?isa.?
? Differentiate between inheritance of interface and inheritance of mplementation.
? Never redefine an inherited nonvirtual function.
? Never redefine an inherited default parameter value.
? Avoid casts down the inheritance hierarchy.
? Model ?has­a? or ?is­implemented­in­terms­of? through layering.
? Differentiate between inheritance and templates.
? Use private inheritance judiciously.
? Use multiple inheritance judiciously.
? Say what you mean; understand what you? re saying.

Miscellany
? Know what functions C++ silently writes and calls.
? Prefer compile­time and link­time errors to runtime errors.
? Ensure that non­local static objects are initialized before they? re used.
? Pay attention to compiler warnings.
? Familiarize yourself with the standard library.
? Improve your understanding of C++.

ViniGodoy

Sobre seu problema em questão, dê uma lida em: http://developers.sun.com/solaris/articles/CC_perf/content.html

Organizar a forma que você faz os includes é importante também para reduzir o tempo de compilação. O que você tem que entender é que sempre que o C++ sentir necessidade de recompilar um .h, ele também irá recompilar todos os arquivos que usam aquele .h.

Portanto, se você puder reclarar as libs no seu .cpp, será melhor do que declara-las no .h. Assim, se uma das libs mudar, o C++ irá recompilar apenas os cpps.

No outro caso, se uma das libs mudar, os .hs serão recompilados, e todos os arquivos que usam aqueles .h. Se esses arquivos forem outros .h, a coisa se espalha e logo você tem o programa inteiro sendo recompilado.

O link acima explica em detalhes essa situação e dá dicas de como organizar seus headers (detalhe, note que os livros que recomendei acima, estão nas referências desse artigo).

Criado 31 de março de 2010
Ultima resposta 31 de mar. de 2010
Respostas 2
Participantes 2