Qt Coding Conventions

C++ features

  • Don’t use exceptions
  • Don’t use rtti (Run-Time Type Information; that is, the typeinfo struct, thedynamic_cast or thetypeid operators, including throwing exceptions)
  • Use templates wisely, not just because you can.

Hint: Use the compile autotest to see whether a C++ feature is supported by all compilers in the test farm.

Conventions in Qt source code

  • All code is ascii only (7-bit characters only, run man ascii if unsure)
    • Rationale: We have too many locales inhouse and an unhealthy mix of UTF-8 and latin1 systems. Usually, characters > 127 can be broken without you even knowing by clickingSAVE in your favourite editor.
    • For strings: Use \nnn (where nnn is the octal representation of whatever character encoding you want your string in) or\xnn (wherenn is hexadecimal). Example:QString s = QString::fromUtf8(”\213\005”);
    • For umlauts in documentation, or other non-ASCII characters, either use qdoc’s \unicode command or use the relevant macro; e.g. \uuml for ü
  • Every QObject subclass must have a Q_OBJECT macro, even if it doesn’t have signals or slots, otherwiseqobject_cast will fail.
  • Normalize the arguments for signals + slots (see QMetaObject::normalizedSignature) inside connect statements to get faster signal/slot lookups. You can use$QTDIR/util/normalize to normalize existing code.

Including headers

  • In public header files, always use this form to include Qt headers: #include <QtCore/qwhatever.h>. The library prefix is neccessary for Mac OS X frameworks and is very convenient for non-qmake projects.
  • In source files, include specialized headers first, then generic headers.
  1.         #include <qstring.h> // Qt class
  2.         #include <new> // STL stuff
  3.         #include <limits.h> // system stuff
  • If you need to include qplatformdefs.h, always include it as thefirst header file.
  • If you need to include qt_x11_p.h, always include it as the last header file.

Casting

  • Avoid C casts, prefer C++ casts (static_cast, const_cast,reinterpret_cast)
    • Rationale: Both reinterpret_cast and C-style casts are dangerous, but at least reinterpret_cast won’t remove the const modifier
  • Don’t use dynamic_cast, use qobject_cast for QObjects or refactor your design, for example by introducing a type() method (see QListWidgetItem)
  • Use the constructor to cast simple types: int(myFloat) instead of(int)myFloat
    • Rationale: When refactoring code, the compiler will instantly let you know if the cast would become dangerous.

Compiler/Platform specific issues

  • Be extremely careful when using the questionmark operator. If the returned types aren’t identical, some compilers generate code that crashes at runtime (you won’t even get a compiler warning).
  1.         QString s ;
  2.         return condition ? s : "nothing" ; // crash at runtime - QString vs. const char *
  • Be extremely careful about alignment.
    • Whenever a pointer is cast such that the required alignment of the target is increased, the resulting code might crash at runtime on some architectures. For example, if aconst char * is cast to anconst int *, it’ll crash on machines where integers have to be aligned at a two- or four-byte boundaries.
    • Use a union to force the compiler to align variables correctly. In the example below, you can be sure that all instances ofAlignHelper are aligned at integer-boundaries.
  1.         union AlignHelper {
  2.             char c ;
  3.             int i ;
  4.         } ;
  • Anything that has a constructor or needs to run code to be initialized cannot be used as global object in library code, since it is undefined when that constructor/code will be run (on first usage, on library load, before main() or not at all). Even if the execution time of the initializer is defined for shared libraries, you’ll get into trouble when moving that code in a plugin or if the library is compiled statically:
  1.         // global scope
  2.         static const QString x ; // Wrong - default constructor needs to be run to initialize x
  3.         static const QString y = "Hello" ; // Wrong - constructor that takes a const char * has to be run
  4.         QString z ; // super wrong
  5.         static const int i = foo ( ) ; // wrong - call time of foo() undefined, might not be called at all

Things you can do:

  1.         // global scope
  2.         static const char x [ ] = "someText" ; // Works - no constructor must be run, x set at compile time
  3.         static int y = 7 ; // Works - y will be set at compile time
  4.         static MyStruct s = { 1 , 2 , 3 } ; // Works - will be initialized statically, no code being run
  5.         static QString *ptr = 0 ; // Pointers to objects are ok - no code needed to be run to initialize ptr

Use Q_GLOBAL_STATIC to create static global objects instead:

  1.         Q_GLOBAL_STATIC ( QString , s )
  2.    
  3.         void foo ( )
  4.         {
  5.             s ( ) -> append ( "moo" ) ;
  6.         }

Note: Static objects in a scope are no problem, the constructor will be run the first time the scope is entered. The code is not reentrant, though.

  • A char is signed or unsigned dependent on the architecture. Use signed char or uchar if you explicitely want a signed/unsigned char. The following code will break on ppc, for example:
  1.         char c = 'A' ;
  2.         if (c < 0 ) { ... } // WRONG - condition is always true on platforms where the default is unsigned char
  • Avoid 64-bit enum values.
    • The aapcs embedded ABI hard codes all enum values to a 32-bit integer.
    • Microsoft compilers don’t support 64-bit enum values. (confirmed with Microsoft ® C/C++ Optimizing Compiler Version 15.00.30729.01 for x64)

Aesthetics

  • Prefer enums to define constants over static const int or defines.
    • enum values will be replaced by the compiler at compile time, resulting in faster code
    • defines are not namespace safe (and look ugly)
  • Prefer verbose argument names in headers.
    • Most IDEs will show the argument names in their completion-box.
    • It will look better in the documentation
    • Bad style: doSomething(QRegion rgn, QPoint p) – use doSomething(QRegion clientRegion, QPoint gravitySource) instead

Things to avoid

  • Do not inherit from template/tool classes
    • The destructors are not virtual, leading to potential memory leaks
    • The symbols are not exported (and mostly inline), leading to interesting symbol clashes.
    • Example: Library A has class Q_EXPORT X: public QList<QVariant> {}; and library B hasclass Q_EXPORT Y: public QList<QVariant> {};. Suddenly, QList<QVariant>‘s symbols are exported from two libraries – /clash/.
  • Don’t mix const and non-const iterators. This will silently crash on broken compilers.
  1.         for (Container :: const_iterator it = c. begin ( ) ; it != c. end ( ) ; ++it ) // W R O N G
  2.         for (Container :: const_iterator it = c. constBegin ( ) ; it != c. constEnd ( ) ; ++it ) // Right
  • Q[Core]Application is a singleton class. There can only be one instance at a time. However, that instance can be destroyed and a new one can be created, which is likely in an <nop>ActiveQt or browser plugin. Code like this will easily break:
  1.         static QObject *obj = 0 ;
  2.         if ( !obj )
  3.             obj = new QObject ( QCoreApplication :: instance ( ) ) ;

If the QCoreApplication application is destroyed, obj will be a dangling pointer. UseQ_GLOBAL_STATIC for static global objects orqAddPostRoutine to clean up.

  • Avoid the use of anonymous namespaces in favor of the static keyword if possible. A name localized to the compilation unit withstatic is guaranteed to have internal linkage. For names declared in anonymous namespaces the C++ standard unfortunately mandates external linkage. (7.1.1/6, or see various discussions about this on the gcc mailing lists)

Binary and Source Compatibility

  • Definitions:
    • Qt 4.0.0 is a major release, Qt 4.1.0 is a minor release, Qt 4.1.1 is a patch release
    • Backward binary compatibility: Code linked to an earlier version of the library keeps working
    • Forward binary compatibility: Code linked to a newer version of the library works with an older library
    • Source code compatibility: Code compiles without modification
  • Keep backward binary compatibility + backward source code compatibility in minor releases
  • Keep backward and forward binary compatibility + forward and backward source code compatibility in patch releases
    • Don’t add/remove any public API (e.g. global functions, public/protected/private methods)
    • Don’t reimplement methods (not even inlines, nor protected/private methods)
    • Check Binary Compatibility Workarounds for ways to keep b/c
  • When writing a QWidget subclass, always reimplement event(), even if it’s empty. This makes sure that the widget can be fixed without breaking binary compatibility.
  • All exported functions from Qt must start with either ‘q’ or ‘Q’. Use the “symbols” autotest to find violations.

Namespacing

  • Read Qt in Namespace and keep in mind that all of Qt except Tests and Webkit is “namespaced” code.

Conventions for public header files

Our public header files have to survive the strict settings of some of our users. All installed headers have to follow these rules:

  • No C style casts (-Wold-style-cast)
    • Use static_cast, const_cast or reinterpret_cast
    • for basic types, use the constructor form: int(a) instead of (int)a
    • See chapter “Casting” for more info
  • No float comparisons (-Wfloat-equal)
    • Use qFuzzyCompare to compare values with a delta
    • Use qIsNull to check whether a float is binary 0, instead of comparing it to 0.0.
  • Don’t hide virtual methods in subclasses (-Woverloaded-virtual)
    • If the baseclass A has a virtual int val() and subclassB an overload with the same name,int val(int x),A‘sval function is hidden. Use theusing keyword to make it visible again, and add the following silly workaround for broken compilers:
  1.         class B : public A
  2.         {
  3.         #ifdef Q_NO_USING_KEYWORD
  4.             inline int val ( ) { return A :: val ( ) ; }
  5.         #else
  6.             using A :: val ;
  7.         #endif
  8.         } ;
  9.  
  • Don’t shadow variables (-Wshadow)
    • avoid things like this->x = x;
    • don’t give variables the same name as functions declared in your class
  • Always check whether a preprocessor variable is defined before probing its value (-Wundef)
  1.         #if Foo ==  0  // W R O N G
  2.         #if defined(Foo) && Foo ==  0 // Right
  3.         #if Foo - 0 ==  0 // Clever, are we? Use the one above instead, for better readability

Categories:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Qt面试中,coding环节通常是测试应聘者Qt编程技能和经验的重要部分。对于Qt面试的coding部分,可能会涉及以下几个方面: 1. Qt基础知识:应聘者需要掌握Qt的基本概念和常用类,了解Qt的对象模型和信号槽机制。可能会出现一些关于Qt类的使用和常见操作的问题。 2. UI设计与开发:这部分可能会要求应聘者根据一些需求或UI设计稿实现一个界面。应聘者需要使用Qt的UI设计工具,例如Qt Designer,完成界面的设计和布局,并用C++代码实现界面的功能。 3. 数据处理与算法:有时候面试官会出一些与数据处理或算法有关的问题,以考察应聘者对Qt的灵活运用能力。例如,要求实现一个基于Qt的文本编辑器,或者对一组数据进行排序等。 4. 多线程编程:对于需要处理并发或耗时操作的问题,可能会考察应聘者的多线程编程能力。这包括使用Qt提供的多线程类或库函数,以及保证线程安全性和避免资源竞争的经验。 5. 调试与问题解决能力:面试过程中可能会有意设置一些错误或问题,观察应聘者的调试和解决问题的能力。应聘者需要能够熟练使用Qt的调试工具,查找和修复代码中的问题和错误。 在Qt面试的coding环节中,关键是熟练掌握Qt的基本特性和常用类,以及对数据处理、UI设计、多线程和问题解决的经验和能力。同时,良好的编码风格和规范也是考察的一项重点。通过练习和实际项目的积累,不断提升自己的Qt编程技能,才能在Qt面试中有较好的表现。 ### 回答2: QT面试coding主要是针对QT编程技能的考察。在QT面试coding过程中,通常会给出一些编程问题或者需要完成一些编程任务。 首先,面试官可能会问一些基础的QT问题,例如QT的信号与槽机制、布局管理器、窗口部件等等。回答这些问题需要我们对QT的相关概念有一定的了解和掌握。 其次,面试官可能会给出一些具体的编程问题,要求我们使用QT进行解答。这些问题可能涉及到QT的各种功能和模块,例如窗口的绘制、界面的响应事件、文件的读写等。在解答这些问题时,我们需要灵活运用QT的相关函数和类进行编程实现。 最后,面试官可能会要求我们完成一些编程任务,例如实现一个简单的QT应用程序、设计一个界面等等。在这些任务中,我们需要运用QT的各种功能和UI设计技巧来完成。 总的来说,QT面试coding主要考察我们对QT编程的熟练程度和实际应用能力。我们需要熟悉QT的相关知识,并能够灵活运用QT进行编程。通过在面试中展示我们的编程能力,我们能够更好地展现自己的优势,提高获得工作机会的几率。 ### 回答3: 在qt面试的coding环节中,通常会要求应聘者完成一个具体的编程任务来评估其在qt开发方面的能力。 首先,面试官可能会询问应聘者是否有qt编程经验以及相关项目经验。这些问题旨在了解应聘者是否熟悉qt框架,是否能够独立开发qt应用程序,并根据具体需求进行调试和优化。 接下来,面试官可能会给应聘者一个具体的编程问题,要求应聘者使用qt编写代码解决该问题。这个问题可能涉及到窗口和控件的创建、布局、信号与槽的连接、界面交互等方面。 在解决问题的过程中,应聘者需要熟悉qt的基本概念和常用的类,比如QWidget、QBoxLayout、QPushButton、QLineEdit等。同时,还需要掌握qt的常用功能,比如事件处理、界面设计和绘图等。 应聘者需要根据问题的要求编写代码,并确保代码的可读性、可维护性和效率。在编程过程中,应聘者需要熟练运用qt的API,同时遵循良好的编码规范,确保代码的质量。 此外,应聘者还可以采取一些额外的措施来提高代码的质量和可扩展性,比如使用设计模式、封装可复用的代码、添加注释和文档等。 最后,面试官可能会与应聘者讨论和评价其代码的质量和实现细节。这个过程中,应聘者需要清楚地解释和展示自己的代码实现,并回答面试官的问题和疑问。 在qt面试的coding环节中,关键是理解问题、熟练使用qt的API和功能,并能够用清晰、简洁、高效的代码解决问题。同时,代码的可读性和可维护性也是重要的考察因素。通过合理的思考和实现,展示自己在qt开发方面的能力和经验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值