Reputation: 33
I'm a complete novice to smart pointers, much less C++, so bear with me here. My program attempts to construct classes with unique serial numbers. It does this by placing already-made serial numbers into a shared_ptr. In theory, this pointer should share the set to all of the classes, but it fails to. This is my class code:
#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. What am I doing wrong here? Thank you for your time.
Upvotes: 0
Views: 478
Reputation: 4727
You seem to misunderstand the concept of shared pointers
. They share ownership, not 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
( 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.)
You barely need a shared pointer in real life. If you want to share the content across instances, you need to make it static.
Upvotes: 3