T 是一个类,它的一个成员 (ptr) 是指向此类对象的指针,但 T 不是指针类。
ptr不是类的成员T。它是类的成员auto_ptr<T>。
ptr 是指向 的指针T。但是,T它不是“指针类”(无论这意味着什么)这一事实并不能阻止某些东西成为指向 a 的指针T。
std::string是一类字符串,而不是指针。
std::string str;是类的对象std::string。
&str是地址str
std::string * ps = &str;
是一个指向std::string.
从一开始:
template <class T> class auto_ptr是一个类模板,其唯一模板参数是class T. 您可以通过为某些实际类指定并声明结果类型的某些对象来实例化模板:T
auto_ptr<std::string> aps;
这给了你另一个实际的类,“auto-pointer-to-string”,它就像:
class auto_ptr_to_string
{
std::string * ptr;
public:
explicit auto_ptr(std::string * p = 0) : ptr(p) {}
~auto_ptr() {delete ptr;}
std::string & operator*() {return *ptr;}
std::string * operator->() {return ptr;}
// ...
};
并且aps是这样定义的对象。
该类有一个数据成员ptr,它是一个指向std::string.
该类还有一个运算符:
std::string & operator*() {return *ptr;}
该运算符定义了将“*”前缀应用于类型的对象所产生的行为auto_ptr<std::string>,例如*aps。
操作符的定义告诉你它返回一个对 an 的引用std::string,并且std::string这个引用所引用的是
*ptr,这意味着“数据成员所引用的那个ptr”。
所以:
auto_ptr<std::string> aps(new std::string("Get it?"));
构造一个auto_ptr<std::string>被调用的,构造函数用指向动态分配的包含“Get it?”的指针aps初始化数据成员。aps.ptrstd::string
和:
std::string s = *aps;
根据 的定义auto_ptr<std::string>::operator*(),声明一个std::string s并用std::string
引用的 by对其进行初始化aps.ptr,即包含“Get it?”的那个。
最后class T,模板参数的语法实际上并没有将它们的值限制为类:auto_ptr<int>例如,虽然int不是类类型,但它很好。我重申迈克西摩关于auto_ptr成为一个坏旧事物的评论。