Home > database >  How to redefine the template class constructor via a macro in C 11?
How to redefine the template class constructor via a macro in C 11?

Time:10-19

I want to recorded the line which created the shared_ptr in C 11. Here is my way to rewrite shared_ptr as 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__);
}

Is there a way to make Shared_ptr<student>Tom(new student(24)) as same as Shared_ptr <student> Tom(new student(24),__ LINE__) in C 11? In other words , invoke class Constructor with the arguments bound to args.

I tried to use marco to achieve,but I don't know the correct way how to define the macro of template class constructor.

Below is the macro definition I tried to write but wrong

template<typename T>
#define Shared_ptr<T>::Shared_ptr(T*) Shared_ptr<T>::Shared_ptr(T * ,__LINE__)

CodePudding user response:

Replace int line=__LINE__ in constructor parameters with int line = __builtin_LINE(). It's a non-standard compiler extension, but it works at least in GCC, Clang, and MSVC (i.e. most common compilers).

Then Shared_ptr<student> Tom(nullptr); will work.


Shared_ptr<student> Tom(42); will not work, because Shared_ptr doesn't have the right constructor, but it has nothing to do with getting the line number.

  •  Tags:  
  • c
  • Related