我想记录创建shared_ptr in C++ 11的行。下面是将shared_ptr重写为Shared_ptr的方法:
template<class T>
class Shared_Ptr{
public:
Shared_Ptr(T* ptr = nullptr,int line=__LINE__)
:_pPtr(ptr)
, _pRefCount(new int(1))
, _pMutex(new mutex)
{
cout<<this<<"is located in "<<line<<endl;
}
~Shared_Ptr()
{
Release();
cout<<this<<endl;
}
Shared_Ptr(const Shared_Ptr<T>& sp)
:_pPtr(sp._pPtr)
, _pRefCount(sp._pRefCount)
, _pMutex(sp._pMutex)
{
AddRefCount();
}
Shared_Ptr<T>& operator=(const Shared_Ptr<T>& sp)
{
//if (this != &sp)
if (_pPtr != sp._pPtr)
{
Release();
_pPtr = sp._pPtr;
_pRefCount = sp._pRefCount;
_pMutex = sp._pMutex;
AddRefCount();
}
return *this;
}
T& operator*(){
return *_pPtr;
}
T* operator->(){
return _pPtr;
}
int UseCount() { return *_pRefCount; }
T* Get() { return _pPtr; }
void AddRefCount()
{
_pMutex->lock();
++(*_pRefCount);
_pMutex->unlock();
}
private:
void Release()
{
bool deleteflag = false;
_pMutex->lock();
if (--(*_pRefCount) == 0)
{
delete _pRefCount;
delete _pPtr;
deleteflag = true;
}
_pMutex->unlock();
if (deleteflag == true)
delete _pMutex;
}
private:
int *_pRefCount;
T* _pPtr;
mutex* _pMutex;
};class student
{
int age;
public:
student(int a):age(a)
{
}
}
;
int main()
{
Shared_ptr<student> Tom(new student(24),__LINE__);
}是否有办法使Shared_ptr<student>Tom(new student(24))与Shared_ptr <student> Tom(new student(24),__ LINE__)在C++11中相同?换句话说,使用绑定到args的参数调用类构造函数。
我试图使用marco来实现,但我不知道如何正确地定义模板类构造函数的宏。
下面是我试图编写但错误的宏定义
template<typename T>
#define Shared_ptr<T>::Shared_ptr(T*) Shared_ptr<T>::Shared_ptr(T * ,__LINE__)发布于 2022-10-19 08:00:24
将构造函数参数中的int line=__LINE__替换为int line = __builtin_LINE()。这是一个非标准的编译器扩展,但它至少在GCC、Clang和MSVC (即大多数普通编译器)中工作。
那么Shared_ptr<student> Tom(nullptr);就能工作了。
Shared_ptr<student> Tom(42);将无法工作,因为Shared_ptr没有正确的构造函数,但与获取行号无关。
https://stackoverflow.com/questions/74121612
复制相似问题