qt 提高代码质量及C++11特性学习

先说代码质量,仅供参考,不过我觉得有一定道理:


① Use multi-arg instead
【不要使用一连串的 arg().arg().arg() 了】

QString("%1 %2").arg(a).arg(b); // Bad
QString("%1 %2").arg(a, b); // one less temporary heap allocation

这个不一定好使,以前用过报错。

② parameter 'list' is passed by value and only copied once; 

consider moving it to avoid unnecessary copies

【多使用右值引用,可以通过 std::move 将参数转化为右值引用】

ChartWidget::ChartWidget(QWidget *parent,QList<int> list) : QWidget(parent), l(list), delt(1.0)
{
} // Bad
 
ChartWidget::ChartWidget(QWidget *parent,QList<int> list) : QWidget(parent), l(std::move(list)), delt(1.0)
{
} // performance unnecessary value param

这个确实想怎么少拷贝一次list,毕竟有时候list有很多东西,至于是不是右值引用少一次拷贝,大家可以分析下


③ the parameter 'table_string' is copied for each invocation but only used as a const reference; consider making it a const reference

【定义函数时,多使用 const &】

void LogData::setupMatrixCam2Veh(QString table_string) // Bad
void LogData::setupMatrixCam2Veh(const QString& table_string)
// performance unnecessary value param

这个const还是要用的,其实可以看qt自己的QLineEdit代码就知道了:

public Q_SLOTS:    
    void setText(const QString &);
    void clear();
    void selectAll();
    void undo();
    void redo();
#ifndef QT_NO_CLIPBOARD
    void cut();
    void copy() const;
    void paste();
#endif

④ constructor does not initialize these fields
【不要忘记初始化类的变量,在头文件的变量旁添加 {} 就可以了】

QToolButton *resetButton; // Bad
QToolButton *resetButton{}; // cppcoreguidelines pro type member init

这个有点扯淡,用指针就直接赋值nullptr呗,没new之前一切免谈。

⑤ use auto when initializing with new to avoid duplicating the type name
【多用auto关键字,尽量使用更现代化的方式来 new】

QHBoxLayout *hl = new QHBoxLayout; // Bad
auto hl = new QHBoxLayout; // modernize use auto

这个可以借鉴,多打字手累,反正编译器能干这个活,语法也是这样定义的。


6、QString高效用法,有个歪果仁写了个不错的blog,可以参考下:https://www.qt.io/blog/efficient-qstring-concatenation-with-c17-fold-expressions


============================华丽的分割线==================================

再说说C++11,我还找有没有C++17的编译器,结果看到一个结论,不知道对不对:

// 截止到目前(2020 年),C++ 的发展历经了以下 3 个个标准: 
// 2011 年,新的 C++ 11 标准诞生,用于取代 C++ 98 标准。此标准还有一个别名,为“C++ 0x”;
// 2014 年,C++ 14 标准发布,该标准库对 C++ 11 标准库做了更优的修改和更新;
// 2017 年底,C++ 17 标准正式颁布。

所以,潜心学好C++11就足够了,多么希望华为能以C11为基础出一套C++框架啊,JAVA太挫了。。。。

C++11学习指南:http://c.biancheng.net/view/7751.html

本文为3YL原创,转载无需联系,但请注明来自labisart.com。

原创文章不易,如果觉得有帮助,可打赏或点击右侧广告支持:

查看打赏记录

发表评论请遵守党国法律!后台审核后方可显示!
  • 最新评论
  • 总共1条评论

Marcellus:对【定义函数时,多使用 const &】这个要加const还是有点意见。其实参考现在的其他语言,例如python,传参都是默认引用。个人理解就是函数里面怎么整都是你自己的事儿。特别是如果void LogData::setupMatrixCam2Veh(const QString& table_string)函数中的table_string要传递给setupMatrixCam2Veh里面的函数。然后套了很多层。万一那天最里面那层突然要去修改这个table_string,那外面层的所有函数又都得改成(QString& table_string)。加引用是支持的,加const就限制有点多余了。

2021-09-27 15:51:16 回复

  • Blog v1.1© 2024 labisart.com 版权所有 | 联系:labartwork@163.com