I want to be able to store data into a data structure, and at some point I want to be able to get pointers to certain elements so that I can reference them directly without having to search. I need to ensure that in the data structure, nothing changes and the values don't somehow get shifted around in memory. I was wondering if there was a way to declare a class member as non const (so that I can read data into it, process, manipulate it as needed) but once I am done populating the data, lock the variable so that it remains unchanged. Thanks
> at some point I want to be able to get pointers to certain elements
> so that I can reference them directly without having to search.
> once I am done populating the data, lock the variable so that it remains unchanged
Make the functions which want to modify objects friends of the class, perhaps.
Another option is to make all the modifications, copy initialise a const qualified object which would be used thereafter, and discard the original mutable object.
If those are not feasible, implement a const lock flag and throw if modifications are attempted after the object is locked for modifications.
I was thinking of making a wrapper class with a bool just like you mentioned. Is there a way to pass on a function call and arguments to a templated member. My thought was something like this...
template<class T>
class const_lock
{
const_lock() : my_lock(false) {}
// HOW TO IMPLEMENT SOMETHING LIKE THIS????
template<typename...Args >
auto operatorANY_OPERATOR (Args...args)
{
static_assert(my_lock == false, "Objected locked to modification");
return my_value.ANY_OPERATOR(args);
}
// HOW TO IMPLEMENT SOMETHING LIKE THIS????
template<typename...Args >
auto ANY_METHOD(Args...args)
{
static_assert(my_lock == false, "Objected locked to modification");
return my_value.ANY_METHOD(args);
}
private:
bool my_lock;
T my_value;
}
This would allow me a simple way to lock any object and still maintain all functionality. I'd also have to figure out how to allow const methods to pass this lock so only non-const methods require a check against my_lock. Any ideas?? Thanks
That seems like it would work. The issue is that you need to have 2 objects of A allocated at the same time (even though you can destroy one later), and copy the data from one to another. This could be extremely inefficient for large data objects. Ideally, I don't want to allocate memory for or move my data once it is in the state I am happy with.
> The issue is that you need to have 2 objects of A allocated at the same time
> (even though you can destroy one later), and copy the data from one to another.
No. There is only one object static A unlocked_a ; in the above example. locked_a is not an object; it is a reference: it is an alias for an object. (No copy is made.)