具有预定义最大使用次数的共享指针

问题描述 投票:0回答:1

有没有办法实现具有编译时已知的最大引用计数的共享指针(可能使用

unique_pointer
)?我的情况是
max_ref_count = 2

const auto p    = std::make_shared<2, double>(2159); //works fine
const auto q    = p; // works fine
const auto err1 = p; // does not compile
const auto err2 = q; // does not compile
c++ shared-ptr smart-pointers unique-ptr
1个回答
0
投票

C++中的标准std::shared_ptr并没有直接提供在编译时设置最大引用计数的机制。但是,您可以通过创建具有有限引用计数的自定义智能指针来实现类似的行为。这是一个基本示例:

#include <iostream>
#include <memory>
#include <stdexcept>

template <typename T, int MaxRefCount = 2>
class LimitedSharedPtr {
public:
    LimitedSharedPtr(T* ptr) : ptr_(ptr), refCount_(1) {
        if (refCount_ > MaxRefCount) {
            throw std::runtime_error("Exceeded maximum reference count");
        }
    }

    LimitedSharedPtr(const LimitedSharedPtr& other) : ptr_(other.ptr_), refCount_(other.refCount_) {
        if (refCount_ > MaxRefCount) {
            throw std::runtime_error("Exceeded maximum reference count");
        }
        refCount_++;
    }

    LimitedSharedPtr& operator=(const LimitedSharedPtr& other) {
        if (this != &other) {
            release();
            ptr_ = other.ptr_;
            refCount_ = other.refCount_;
            if (refCount_ > MaxRefCount) {
                throw std::runtime_error("Exceeded maximum reference count");
            }
            refCount_++;
        }
        return *this;
    }

    ~LimitedSharedPtr() {
        release();
    }

    T* get() const {
        return ptr_;
    }

private:
    void release() {
        refCount_--;
        if (refCount_ == 0) {
            delete ptr_;
        }
    }

    T* ptr_;
    int refCount_;
};

int main() {
    LimitedSharedPtr<double, 2> p(new double(2159));
    LimitedSharedPtr<double, 2> q = p; // works fine
    LimitedSharedPtr<double, 2> err1 = p; // throws runtime_error
    LimitedSharedPtr<double, 2> err2 = q; // throws runtime_error

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.