cs_libguarded
cs_libguarded copied to clipboard
Intended design for use within const methods?
Ran into a problem. I wanted to use a plain_guarded to wrap a member variable. I have a getter to return a copy of that member variable:
class thing {
private:
plain_guarded<int> x_;
public:
int get_x() const {
return *x_.lock(); // error! discards qualifiers
}
};
I can't do this, because x_.lock() is not a const operation. I can const_cast x_, or make it mutable. The former is unergonomic and slightly dangerous, and the latter is dangerous because it too easily allows mutation of the underlying variable.
I suggest a const version of the lock() method (and friends) which returns a std::unique_ptr<const T, deleter> (perhaps aliased to a const_handle, like iterator/const_iterator). This would push the mutable down into the internal mutex member instead of users needing to care.
const methods that mutate an internal mutex has precedent in the std::atomic<T>::load() method, which is marked const despite mutating its internal mutex (in the case of non-lock-free instantiations).
Thanks for the suggestion. This has been added in 707efec, let me know if this implementation addresses your use case.
Closing as resolved, feel free to reopen if there are any remaining questions.