Just to give a context, this is a simple version of my code:
class myqueue
{
struct readable
{
readable()
{
static int __next = 0;
id = __next++;
}
int id;
};
std::list<readable> readers;
public:
readable& sub(){
readers.emplace_back();
return readers.back();
}
void unsub(readable& reader)
{
for (auto it = readers.begin(); it != readers.end(); ++it)
{
if (it->id == reader.id)
{
readers.erase(it);
break;
}
}
}
};
int main()
{
myqueue q;
auto& read = q.sub();
q.unsub(read);
return 0;
}
With this code, after the call to unsub()
, the reference you got from sub()
is no longer valid, right?
Is there a better (secure) way to handle this situation and be sure noone will keep using that reference?
The first alternative I can think of is to check for the validity at runtime using pointers instead of references, but it's something you have to do explicitly every time and you can also skip/forget that. It would be great to be able to catch any use of that reference after the unsub()
at compile time (something like Rust do after moving objects).
Is there any way to achieve this?
I think this is pretty simple to do logically:
- Get
something
fromsub()
- use it
- call
unsub()
- if that
something
appears again in this block => XXX
Probably with a static analyzer is simply doable, I was just wandering if I can achieve this during the compile.