C ++ - 什么时候应该在类中使用指针成员
在学习C ++(和Direct3D,但是前一段时间)时,我一直困惑的是,你应该在类中使用指针成员。例如,我可以使用非指针声明:
One of the thing that has been confusing for me while learning C++ (and Direct3D, but that some time ago) is when you should use a pointer member in a class. For example, I can use a non-pointer declaration:
private:
SomeClass instance_;
或者我可以使用指针声明
Or I could use a pointer declaration
private:
Someclass * instance_
在构造函数中使用new()。
And then use new() on it in the constructor.
我知道如果SomeClass可以派生自另一个类,一个COM对象或是一个ABC,那么它应该是一个指针。
I understand that if SomeClass could be derived from another class, a COM object or is an ABC then it should be a pointer. Are there any other guidelines that I should be aware of?
指针具有以下优点:
a)你可以做一个延迟初始化,这意味着在第一次实际使用之前只需要短暂的初始化/创建对象。
a) You can do a lazy initialization, that means to init / create the object only short before the first real usage.
b)设计:如果你为外部类类型的成员使用指针,你可以在你的类上面放置一个向前的声明,因此不需要在你的头中包含该类型的头部 - 而不是包括第三方头部在您的.cpp中,这有利于减少编译时间,并通过包含太多其他标头来防止副作用。
b) The design: if you use pointers for members of an external class type, you can place a forward declaration above your class and thus don't need to include the headers of that types in your header - instead of that you include the third party headers in your .cpp - that has the advantage to reduce the compile time and prevents side effects by including too many other headers.
class ExtCamera; // forward declaration to external class type in "ExtCamera.h"
class MyCamera {
public:
MyCamera() : m_pCamera(0) { }
void init(const ExtCamera &cam);
private:
ExtCamera *m_pCamera; // do not use it in inline code inside header!
};
c)指针可以随时删除 - 所以你可以更多地控制生命周期,创建一个对象 - 例如在失败的情况下。
c) A pointer can be deleted anytime - so you have more control about the livetime and can re-create an object - for example in case of a failure.