错误修复器

工程开发 社区

技能解读

当前原文的自动摘译,尚未人工审校。

概述

通过最少的 Qt 风格更改来诊断和修复 Qt C++ 错误。铁律:仅修复报告的问题。没有额外的重构,没有“当我在这里”的改进。

何时使用

编译错误:undefined reference to 'vtable'、缺少Q_OBJECT、MOC 错误、循环包含、CMakeLists.txt/.pro 问题运行时崩溃:分段错误、空指针取消引用、纯虚拟调用内存问题:new 没有 delete、不正确的父子关系、泄漏 UI 问题:小部件不显示、布局失败、信号槽不存在控制装置工作但无反应

快速参考

Bug 类型 · 根本原因 · 最小修复 undefined reference to 'vtable' · 缺少 Q_OBJECT 宏 · 在标头 moc 文件中取消注释/添加 Q_OBJECT 未生成 · 标头不在 CMakeLists.txt/.pro 中 · 将标头添加到构建文件 nullptr 上的段错误 · 取消引用之前没有 null 检查 · 使用前添加 if (ptr) 内存泄漏 · new 无父级所有权 · 将父级添加到 new 或使用 deleteLater()

1. 诊断阶段

仔细阅读错误:编译错误→查找行号;运行时崩溃→读取回溯; UI 问题 → 注意具体行为 定位有问题的代码:使用 @file:line 表示法,读取上下文(类定义、包含、父级),检查相关文件 检查 Qt 上下文:类是否继承 QObject? Q_OBJECT 存在吗?亲子关系正确吗?信号/插槽是否已连接?

2 假设与验证

生成 1-2 个根本原因:关注错误类型(MOC/config、内存/null、信号/布局、线程关联) 验证假设:检查代码 - 不要假设。 MOC错误总是涉及Q_OBJECT和元对象系统

流狐档案 运行与权限由流狐静态检查推断,不代表作者声明或实际测试结果。
领域
工程开发
作者声明的智能体
未找到明确声明;不据此推断已兼容或已测试
静态检查
88 / 100 · 启发式扫描,不代表运行安全
运行环境证据
未执行;当前没有隔离运行测试证据
作者 / 版本 / 许可证
@re2zero · 未声明许可证
上下文用量评级
低消耗
接入复杂程度
需简单配置
是否需要外部接口密钥
不需要
兼容的系统
未声明(默认跨平台)
运行环境要求
未检出明确要求
检测到的文件与系统行为
  • 只读
  • 允许写入 / 修改
  • 命令执行
网络行为
仅限本地
安装命令数
无(仅作为资料)

需要注意: 未声明工具权限范围;实际权限由运行环境决定。

作者说明文件(原文) SKILL.md

# Qt C++ Bug Fixer

## Overview

Diagnose and fix Qt C++ bugs with minimal, Qt-style changes. **Iron Rule: Fix ONLY the reported issue.** No extra refactoring, no "while I'm here" improvements.

## When to Use

**Compilation Errors:** `undefined reference to 'vtable'`, missing `Q_OBJECT`, MOC errors, circular includes, CMakeLists.txt/.pro issues

**Runtime Crashes:** Segmentation faults, null pointer dereferences, pure virtual calls

**Memory Issues:** `new` without `delete`, incorrect parent-child relationships, leaks

**UI Problems:** Widgets not displaying, layout failures, signal-slot not working, unresponsive controls

**Threading:** Cross-thread UI crashes, thread affinity, blocking UI thread

**Do NOT use when:** Intentionally refactoring, adding features (use TDD), or performance optimization

## Core Pattern

```cpp
// ❌ WRONG: Refactoring while fixing
void MyWidget::processData()
{
    if (m_processor) {
        auto dataProcessor = m_processor;  // UNNECESSARY rename
        QList<int> items = dataProcessor->getItems();  // UNNECESSARY STL→Qt
        qDebug() << "Processing" << items.size();  // UNNECESSARY logging
    }
}

// ✅ CORRECT: Only the fix
void MyWidget::processData()
{
    if (m_processor) {  // Fix: Added null check
        m_processor->process();
    }
}
```

```cpp
// ❌ WRONG: External smart pointers
#include <memory>
std::unique_ptr<DataProcessor> m_processor;

// ✅ CORRECT: Qt parent-child ownership
DataProcessor *m_processor = new DataProcessor(this);  // Parent handles deletion
```

## Quick Reference

| Bug Type | Root Cause | Minimal Fix |
|----------|------------|-------------|
| `undefined reference to 'vtable'` | Missing `Q_OBJECT` macro | Uncomment/add `Q_OBJECT` in header |
| `moc` file not generated | Header not in CMakeLists.txt/.pro | Add header to build files |
| Segfault on nullptr | No null check before dereferencing | Add `if (ptr)` before use |
| Memory leak | `new` without parent ownership | Add parent to `new` or use `deleteLater()` |
| Signal not firing | Connection broken or wrong signature | Check `connect()` syntax and lifetime |
| Cross-thread UI crash | Direct UI manipulation from worker | Use `QMetaObject::invokeMethod` or signal-slot |

## Implementation

### 1. Diagnostic Phase

**Read error carefully:** Compiler error → find line number; Runtime crash → read backtrace; UI issue → note specific behavior

**Locate problematic code:** Use `@file:line` notation, read context (class definition, includes, parent), check related files

**Check Qt context:** Does class inherit `QObject`? Is `Q_OBJECT` present? Are parent-child relationships correct? Are signals/slots connected?

### 2. Hypothesis and Verification

**Generate 1-2 root causes:** Focus on error type (MOC/config, memory/null, signals/layout, thread affinity)

**Verify hypothesis:** Check code - don't assume. MOC errors always involve `Q_OBJECT` and meta-object system

### 3. Generate Minimal Fix

**Fix ONLY the identified issue:** ONE problem = ONE fix. No variable renames, no style cleanup, no optimizations

**Explain WHY:** Root cause, not symptom. Qt-specific mechanics (MOC, parent-child, signal-slot)

**Explain HOW:** Principle behind change. Why it solves root cause

**Regression testing:** Compile (`cmake --build .` or `make`), suggest specific verification steps, run tests if applicable

### 4. Configuration File Fixes

**CMakeLists.txt:**
```cmake
qt_add_executable(MyApp
    main.cpp
    mywidget.h  # MUST include header with Q_OBJECT
    mywidget.cpp
)
```

**.pro file:**
```qmake
HEADERS += mywidget.h  # Headers with Q_OBJECT must be listed
SOURCES += mywidget.cpp
```

## Common Mistakes

| Mistake | Why Wrong | Correct |
|---------|-----------|---------|
| Renaming variables while fixing | Violates minimal change principle | Keep existing names |
| "Upgrading" SIGNAL/SLOT to lambda | Unnecessary change, breaks code | Fix only broken connection |
| Converting STL to Qt containers | Unrelated to bug | Fix only what causes crash |
| Adding logging "for debugging" | Extra code not needed | Fix root cause directly |
| Adding null checks everywhere | Masks real problem | Add only where crash occurs |
| Refactoring while fixing | Scope creep, introduces bugs | ONE fix per bug report |

## Rationalization Table

| Excuse | Reality |
|--------|---------|
| "This variable name is confusing, I'll rename it" | Variable names don't cause crashes. Fix the crash. |
| "While I'm here, let me upgrade to modern Qt syntax" | Technical debt is not a bug. Fix the bug. |
| "This cleanup makes the code clearer" | Clarity improvements are refactoring, not bug fixing. |
| "The old SIGNAL/SLOT macros are deprecated" | Deprecated ≠ broken. Fix only what's broken. |
| "I'm adding a safeguard, it's defensive programming" | Safeguards without justification are extra code. Fix root cause. |
| "This refactoring is minimal and obvious" | Any change beyond the fix is NOT minimal. |
| "I'll improve the design while fixing it" | Design improvements are separate tasks. Fix the bug. |
| "It's about quality, not just functionality" | Quality bug fixes focus on minimal, surgical changes. |

## Red Flags - STOP and Start Over

**STOP immediately** if you think or say ANY of these:

- "While I'm fixing this, I'll also..."
- "This is a good opportunity to clean up..."
- "The old style should be modernized..."
- "I'll add a safeguard/precaution..."
- "This variable name is confusing, better rename it..."
- "Let me upgrade to the latest Qt API..."
- "This design could be improved..."
- "I'll make it more robust/defensive..."
- "This code is messy, let me organize it..."

**ALL mean:** You're doing MORE than fixing the bug. Stop. Delete extra changes. Fix ONLY the reported issue.

## Qt-Specific Anti-Patterns

**Avoid External Smart Pointers:**
```cpp
// ❌ std::unique_ptr
std::unique_ptr<QWidget> m_widget;
// ✅ Qt parent-child
QWidget *m_widget = new QWidget(this);
```

**Thread-Aware Connections:**
```cpp
// ❌ Wrong affinity assumption
workerThread->start();
worker->doWork();  // Might crash
// ✅ Qt 5 explicit type
connect(worker, &Worker::finished, this, [this]() {}, Qt::QueuedConnection);
```

**Qt Blocking Helpers:**
```cpp
// ❌ Manual locks
QMutexLocker locker(&m_mutex);
// ✅ Qt's QSignalBlocker
QSignalBlocker blocker(this);  // Auto-unblocks on scope exit
```

**Memory Management:**
```cpp
// ❌ Manual delete
MyWidget *w = new MyWidget();
delete w;
// ✅ Parent-child system
MyWidget *w = new MyWidget(this);  // Parent deletes on destruction
```

## Backward Compatibility

**CRITICAL:** Verify fix doesn't break existing connections:
1. Check all `connect()` calls to/from modified object
2. Verify object lifetime doesn't break parents/children
3. Don't change signal/slot signatures unless that's the bug
4. Don't remove connections unless causing the issue

## The Iron Law

**Fixing bugs is NOT an excuse for refactoring.**

Every change beyond the minimal fix introduces new risk, wastes user's time, violates the contract of "bug fix."

**When in doubt:** Ask yourself "Would this change be justified if I only said I was fixing the bug, not 'cleaning up'?"

If NO → Delete the change. Fix ONLY the bug.

**No exceptions:**
- Not for "obvious" improvements
- Not for "technical debt" reduction
- Not for "best practices" alignment
- Not for "making it clearer"
- Not for "while I'm here"
- Minimal fix means MINIMAL

讨论

基于 GitHub Discussions。登录 GitHub 即可参与讨论、点赞、订阅更新。