Qt 為什麼要有 QScopedPointer 呢?

不久前在 Qt Labs Blogs 上的一篇文章引起了我的注意,文章標題是:Introducing QScopedPointer ,介紹了即將在 Qt 4.6 現身的新成員 — QScopedPointer , Qt 4.6 的 preview 也已經放進了相關的文件。在 C++ 中使用 RAII 的手法是相當常見的,而且也納入標準之中的,或是 boost 也提供了 Smart Pointers library

為什麼 Qt 需要提供自己一套 Smart pointers 呢?

Qt 背後的動機令我感到好奇,一如我在 KAutoPointer: a new autoptr class for QPointer 討論串上看到鄉民 Ingo Klöcker 說的:

... Unfortunately, there appears to be quite some aversion against using boost's pointer template classes (a trivial compile time dependency) in KDE …

而的確,這也引起了一陣討論,下面收集了一些討論來瞭解一下:

  1. QT Labs Blogs:
    1. Introducing QScopedPointer
    2. Count with me: how many smart pointer classes does Qt have
    3. Some more pointing
  2. Mailing list or news
    1. KAutoPointer: a new autoptr class for QPointer
    2. OS news: Introducing QScopedPointer

題外話一下:有沒有興趣猜猜 Qt 提供了幾種 smart pointers 呢?在 Count with me: how many smart pointer classes does Qt have? 一文中列出了八種:

  1. QPointer (4.0)
  2. QSharedDataPointer (4.0)
  3. QExplicitlySharedDataPointer (4.3/4.4)
  4. QtPatternist::AutoPtr (internal class, 4.4)
  5. QSharedPointer (4.5)
  6. QWeakPointer (4.5)
  7. QGuard (internal class, 4.6)
  8. QScopedPointer (4.6)

呵呵(或,科科),是不是很有趣呢?回到正題, Count with me: how many smart pointer classes does Qt have? 一文解釋了為什麼不採用既有的 scoped pointers:

  1. C++0x 尚未通過,其實作也只有在 GCC 4.3 之後以及 MSVC 2010 beta 中才有;
  2. TR1 的實作品不夠;
  3. Boost 呢,ㄜ,Qt 認為它是“un-Qt-ish” API,或者該說是“horrible API”,這句話其實是沒有惡意的,只是想說兩者的命名哲學不同。此外,Qt 與 KDE 對於 binary compatibility 有著嚴格、複雜的要求,若是採用 boost 實作會破壞這相容性。(如果有興趣,可以參考一下 KDE TechBase 上的一篇文章:Policies/Binary Compatibility Issues With C++ ,最近的貢獻者就是 Count with me … 一文的作者: Thiago Macieira。)
  4. Qt 還是希望握有 scoped pointer 的 knowledge。

在我看來, Qt 期許自己成為一個成熟易用又跨平台的函式庫,它的支援環境可能沒有完整的標準 C++ 函式庫,又因為 C++ 缺乏統一的 ABI 支援,在某些應用上若沒有一些事先規範會讓事情發展到某種程度後窒礙難行,至於有多窒礙難行呢?我還不能說個所以然,因為自己沒有真的痛過,無法把那種罄竹難書講得感同身受 Orz …

延伸閱讀:

一些關於 ABI 、binary compatibility、modular mechanism 的討論:

  1. Qt Labs Blogs: Some thoughts on calling convention
  2. Qt Labs Blogs: Some thoughts on binary compatibility
  3. Imperfect C++: Part 2 - Surviving The Real World
  4. Essential COM: COM as a Better C++
  5. C++0x 有過相關的討論:
    1. Modules in C++
    2. Draft Proposal for Dynamic Libraries in C++
    3. 不過被打槍了!

沒有留言:

Windows + Visual Studio + VSCode + CMake 的疑難雜症

Environment Windows 10 Visual Studio 2019 CMake 3.27.7 VSCode VSCode CMake Tools 1. CMAKE_BUILD_TYPE 是空的 參考一下 這篇 的處理。 大致上因為 Visual...