这行/语法是什么意思?
What does this line/syntax mean?
#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);
这样做:
- 使用默认的
Resource
分配器为new
实例分配内存(即操作系统提供的堆(。 - 该新
Resource
实例的地址将传递到Auto_ptr1
的构造函数中。- 然后将其存储在
res
值内的m_ptr
中。
- 然后将其存储在
- 当
res
超出范围时,将调用Resource
实例的析构函数。
我很欣赏这看起来像一个学习练习,这很好,我鼓励更多的人重新实现标准库组件,以了解它们是如何工作的,并培养对它们的欣赏 - 但我不建议在生产中使用此代码(因为这是同行评审的 STL 和 Boost 库的目的(。
正如 @Igor Tandetnik 所说,它创建了一个类模板的实例,Auto_ptr1
类型为Resource
称为res
,它使用指向新的动态分配Resource
的指针进行初始化。
相关文章:
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- "类模板示例<int>;"语句对 C++11 是什么意思?
- 线应该是什么意思
- "CID"在AT+HTTPPARA= "CID" ,1中是什么意思
- 表达式"b=(b-x)&x"是什么意思?
- 这个表达是什么意思?
- 此代码验证公式是什么意思?
- 跟踪日志中的T.11803()是什么意思?
- 这个额外的关键字在这个 c++ 类声明中是什么意思?
- * 和 ** 在 C++ 函数声明中是什么意思?
- _T("xyz")是什么意思?
- #define Dbg(fmt,..) (0) 是什么意思? 警告:表达式无效
- 这行代码到底是什么意思?
- 当我们说在执行程序时将操作系统的控制权传递给main()函数时,我们的意思是什么
- 这句话在c++中的意思是什么
- 这个typedef的意思是什么
- 这句话的意思是什么
- 意思是什么
- 这个句法的意思是什么?