Qt 标题中的QScopedPointer声明,src中的定义

Qt 标题中的QScopedPointer声明,src中的定义,qt,Qt,能否在标题中声明QScopedPointer: QScopedPointer <T> _name; 注意:我知道QScopedPointer没有操作符来做这件事,只有一个ctor,但是从概念上讲,这可以以某种方式实现吗 我们可以在标题中使用QScopedPointer类型的类成员吗 班级宣言 对。确保定义或声明了类型T: /// /// File MyClass.h /// // Either have: #include "MyType.h" // defines MyType

能否在标题中声明QScopedPointer:

QScopedPointer <T> _name;
注意:我知道QScopedPointer没有操作符来做这件事,只有一个ctor,但是从概念上讲,这可以以某种方式实现吗

我们可以在标题中使用QScopedPointer类型的类成员吗 班级宣言

对。确保定义或声明了类型T:

///
/// File MyClass.h
///

// Either have:
#include "MyType.h" // defines MyType

// Or:
class MyType; // forward declaraion

class MyClass
{
public:
    MyClass();
    ////
private:
    QScopedPointer<MyType> m_pTypeObj;
};
或者正如作者所暗示的:

MyClass::MyClass() : m_pTypeObj(new MyType)
{
    // and use the scoped pointer
    m_pTypeObj->method();
}

该方法也适用于现在可以替换的对象。

第一个示例不会编译,因为默认dtor需要对象的定义。如果要将QScopedPointer与转发声明一起使用,则必须在.cpp文件中定义dtor。正确:*但应始终在实例化对象的位置定义类型*
#include "MyClass.h" // defines MyClass
// If not through MyClass.h then must have:
#include "MyType.h"  // defines MyType

MyClass::MyClass()
{
    // now we can instantiate MyType
    m_pTypeObj.reset(new MyType);
    // and use the scoped pointer
    m_pTypeObj->method();
}
MyClass::MyClass() : m_pTypeObj(new MyType)
{
    // and use the scoped pointer
    m_pTypeObj->method();
}