这行/语法是什么意思?

What does this line/syntax mean?

本文关键字:意思 是什么 语法 这行      更新时间:2023-10-16
#include <iostream>
template<class T>
class Auto_ptr1
{
T* m_ptr;
public:
// Pass in a pointer to "own" via the constructor
Auto_ptr1(T* ptr=nullptr)
:m_ptr(ptr)
{
}
// The destructor will make sure it gets deallocated
~Auto_ptr1()
{
delete m_ptr;
}
// Overload dereference and operator-> so we can use Auto_ptr1 like m_ptr.
T& operator*() const { return *m_ptr; }
T* operator->() const { return m_ptr; }
};
// A sample class to prove the above works
class Resource
{
public:
Resource() { std::cout << "Resource acquiredn"; }
~Resource() { std::cout << "Resource destroyedn"; }
};
int main()
{
Auto_ptr1<Resource> res(new Resource); // Note the allocation of memory here
// ... but no explicit delete needed
// Also note that the Resource in angled braces doesn't need a * symbol, since that's supplied by the template
return 0;
} // res goes out of scope here, and destroys the allocated Resource for us

我想知道这一行中的语法是什么意思,我以前从未使用过:

Auto_ptr1<Resource> res(new Resource); // Note the allocation of memory here

我尝试在谷歌上搜索它,但没有任何结果,即使有,我也不知道如何构建适当的问题,所以我为此跳上了 StackOverflow。

  • Auto_ptr1看起来像是C++STLunique_ptr的(糟糕的(重新实现。
  • 因此,它是一个"智能指针",它限制父实例Auto_ptr1实例的生存期m_ptr指向的堆分配数据的生存期。

分解一下:

Auto_ptr1<Resource> res(new Resource); 

这样做:

  1. 使用默认的Resource分配器为new实例分配内存(即操作系统提供的堆(。
  2. 该新Resource实例的地址将传递到Auto_ptr1的构造函数中。
    • 然后将其存储在res值内的m_ptr中。
  3. res超出范围时,将调用Resource实例的析构函数。

我很欣赏这看起来像一个学习练习,这很好,我鼓励更多的人重新实现标准库组件,以了解它们是如何工作的,并培养对它们的欣赏 - 但我不建议在生产中使用此代码(因为这是同行评审的 STL 和 Boost 库的目的(。

正如 @Igor Tandetnik 所说,它创建了一个类模板的实例,Auto_ptr1类型为Resource称为res,它使用指向新的动态分配Resource的指针进行初始化。