简体   繁体   English

C++ Shared_Ptr 不共享?

[英]C++ Shared_Ptr not sharing?

I'm a complete novice to smart pointers, much less C++, so bear with me here.我是智能指针的新手,更不用说 C++,所以请耐心等待。 My program attempts to construct classes with unique serial numbers.我的程序尝试构建具有唯一序列号的类。 It does this by placing already-made serial numbers into a shared_ptr.它通过将已经制作的序列号放入 shared_ptr 中来做到这一点。 In theory, this pointer should share the set to all of the classes, but it fails to.理论上,该指针应该与所有类共享该集合,但它失败了。 This is my class code:这是我的 class 代码:

#include <iostream>
#include <cstdlib>
#include <set>
#include <memory>
#include <algorithm>

struct numbered{
    numbered();
    int mysn;
    std::shared_ptr<std::set<int>> catalogue = std::make_shared<std::set<int>> ();
};

numbered::numbered(){
    while (true){
        int check = rand() & 100; 
        if(catalogue->find(check) == catalogue->end()){  // if this number is not already in the catalogue
            mysn = check; // make this the serial number
            // add this to the log of illegal serial numbers
            catalogue->insert(mysn);
            return; // stop making new numbers to check for            
        }
        else{ // temporary provision, just to get this to work
            mysn = 5;
            return;
        }
    }
}

This is my main code:这是我的主要代码:

#include <iostream>
#include "numberedheader.hpp"

using namespace std;

int main(){
    numbered a, b;
    cout << a.mysn << " " << b.mysn << endl;
    system("pause");
    return 0;
}

I've ran some tests.我已经进行了一些测试。 Catalogue is able to find ints and is able to update to include the newest ints, however, there seems to be a new catalogue set for every class rather than one shared one.目录能够找到整数并且能够更新以包含最新的整数,但是,似乎每个 class 都有一个新的目录集,而不是一个共享的目录集。 What am I doing wrong here?我在这里做错了什么? Thank you for your time.感谢您的时间。

You seem to misunderstand the concept of shared pointers .您似乎误解了shared pointers的概念。 They share ownership , not memory .他们共享所有权而不是memory Smart Pointers are all about ownership.智能指针都是关于所有权的。

With a shared pointer, the memory it owns is kept alive as long as there are objects referencing it使用共享指针,只要有引用它的对象,它拥有的 memory 就会保持活动状态
( different with a unique pointer where only one can own this memory. if this single reference is destroyed, the memory owned by a unique ptr is destroyed automatically.) (与唯一指针不同,其中只有一个人可以拥有此 memory。如果此单个引用被破坏,则由唯一 ptr 拥有的 memory 将自动销毁。)

You barely need a shared pointer in real life.在现实生活中,您几乎不需要共享指针。 If you want to share the content across instances, you need to make it static.如果要跨实例共享内容,则需要将其设为 static。

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

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