在结构中声明并初始化 unique_ptr

时间:2021-06-08 19:14:41

标签: c++ smart-pointers unique-ptr

我想知道如何在结构中声明一个唯一的 ptr 并稍后对其进行初始化。现在我有

bubbleSort2(x, tot,line)

void bubbleSort2(int arr[], int n,char line[128][20])
{
    int c,d;
    int swap;
    for (c = 0; c < n - 1; c++)
    {
        for (d = 0; d < n - c - 1; d++)
        {
            if (arr[d] < arr[d + 1])
            {
                swap = arr[d];
                arr[d] = arr[d + 1];
                arr[d + 1] = swap;
                swap(line[d],line[d+1]);
            }
        }
    }
}

但是我收到一条错误消息,说

struct CacheObject {
    std::string _cache_type; 
    std::unique_ptr<faiss::Cache> cache; 

    uint64_t _cache_size;
    // Real time data 
    int64_t rt_byte_req;
    int64_t rt_byte_miss;
    int64_t rt_obj_req;
    int64_t rt_obj_miss;

    CacheObject();
};

为什么会发生这种情况,我该如何修改?谢谢!

2 个答案:

答案 0 :(得分:2)

std::unique_ptr 无法复制,只能移动,因此编译器无法为您的结构生成复制赋值 operator=。因此,像 arg2 = *temp; 这样的语句(其中 arg2*tempCacheObject 对象)在默认情况下不起作用。

您需要实现自己的复制赋值 operator= 来克隆 faiss::Cache 对象,例如:

struct CacheObject {
    ...
    std::unique_ptr<faiss::Cache> cache; 
    ...

    CacheObject& operator=(const CacheObject &rhs)
    {
        if (this != &rhs)
        {
            if (rhs.cache)
                cache.reset(new faiss::Cache(*(rhs.cache))); // or equivalent...
            else
                cache.reset();

            // copy other members as needed...
        }
        return *this;
    }
};

...

arg2 = *temp;

和/或,实现移动赋值 operator= 以将 unique_ptr 从一个 CacheObject 移动到另一个,例如:

struct CacheObject {
    ...
    std::unique_ptr<faiss::Cache> cache; 
    ...

    CacheObject& operator=(CacheObject &&rhs)
    {
        cache = std::move(rhs.cache);
        // move other members as needed...
        return *this;
    }
};

...

arg2 = std::move(*temp);

答案 1 :(得分:0)

这是对@remylebeau 已经提到的内容的修正。 reset() 也有 struct CacheObject { // .... void SetCacheObject(faiss::Cache* p) { if (p) { // This assumes you're resetting it because you no longer // care about what it pointed to delete cache.release(); } cache.reset(p); } }; void SomeFunc() { CacheObject co; // ... elsewhere and after important stuff co.SetCacheObject(new faiss::Cache()); } 成员函数。你也可以这样

std::unique_ptr<faiss::Cache>

您可以参考 this link for resetthis link for release

编辑

经过一些思考后,我认为重要的是要提及如果您应该使用这种方法并且 {{1}} 对象具有有效引用,否则您将泄漏内存,除非您妥善处理。我已经用一种可能的方法来防止这种情况发生。

相关问题