简体   繁体   English

C++ 中的指针构造函数

[英]Pointer Constructor in C++

I'm asked to write a SmartPointer class.我被要求写一个SmartPointer class。 One of the constructors takes a pointer variable, and I assume that I should simply copy the pointer to the relevant variable.其中一个构造函数采用指针变量,我假设我应该简单地将指针复制到相关变量。 But when I try, I get a segmentation error.但是当我尝试时,我得到一个分段错误。 Here is the content of the header file and my implementation of Pointer Constructor .这是 header 文件的内容和我对Pointer Constructor的实现。

class ReferenceCount {
public:
    size_t AddRef() {
        return ++count;
    }

    size_t Release() {
        return --count;
    }

    size_t getCount() const {
        return count;
    }

private:
    size_t count = 0; // Reference count
};



template<typename T>
class SmartPointer {

private:
    void free();
    // pointer to actual data
    T *dataPointer;
    // Reference count
    ReferenceCount *referenceCount;

public:
    //Constructor
    SmartPointer();

    // Copy constructor
    SmartPointer(const SmartPointer<T> &sp);

    explicit SmartPointer(T *pValue);

    // Assignment operator
    SmartPointer<T> &operator=(const SmartPointer<T> &sp);

    SmartPointer<T> &operator=(T *pValue);

    // Destructor
    ~SmartPointer();

    T &operator*() const;

    T *operator->() const;

    T *get() const;

    ReferenceCount *getReferenceCount() const;

};

The constructor:构造函数:

template<typename T>
SmartPointer<T>::SmartPointer(T *pValue) {
    dataPointer = pValue;
    referenceCount = nullptr;
}

You appear to be writing something similar to shared_ptr<T> .您似乎正在编写类似于shared_ptr<T>的内容。

For a shared_ptr -like smart pointer, each smart pointer has both a pointer-to-object and a pointer-to-control-block.对于一个shared_ptr的智能指针,每个智能指针都有一个指向对象的指针和一个指向控制块的指针。

When you are constructed with a pointer-to-object, you are responsible to create the control block.当您使用指向对象的指针构造时,您负责创建控制块。

In your case, your control block name is ReferenceCount .在您的情况下,您的控制块名称是ReferenceCount

So add a new ReferenceCount to that constructor.因此,向该构造函数添加一个new ReferenceCount Probably start it off with a count of 1.可能从计数 1 开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM