Skip to content

Instantly share code, notes, and snippets.

@matthiasvegh
Created December 19, 2013 09:07
Show Gist options
  • Save matthiasvegh/8036480 to your computer and use it in GitHub Desktop.
Save matthiasvegh/8036480 to your computer and use it in GitHub Desktop.
If a class has several non-const functions, these should all contain a lock_guard, however placing this in every function implementation can be too verbose, this is a possible workaround.
#include <iostream>
#include <mutex>
#include <vector>
class Bar { };
class Foo1 {
std::mutex _mutex;
std::vector<Bar> _data;
public:
void doStuff() {
_mutex.lock();
std::cout<<"doStuff"<<std::endl;
_mutex.unlock();
}
Bar getStuff() const {
return Bar{};
}
// have to add the lock_guard to all write non-const operations, Foo2 solves this.
};
class Data {
public:
std::mutex _mutex;
std::vector<Bar> _data;
virtual ~Data() { }
};
class NonConstInterface: public virtual Data {
public:
NonConstInterface() {
this->_mutex.lock();
}
~NonConstInterface() {
this->_mutex.unlock();
}
void doStuff() {
std::cout<<"doStuff"<<std::endl;
}
};
class ConstInterface: public virtual Data {
public:
Bar getStuff() const {
return Bar{};
}
};
class Foo2: public ConstInterface, private NonConstInterface {
public:
NonConstInterface& getNonConst() {
return *this;
}
};
int main() {
Foo2 f;
// f.doStuff(); fails :D
auto& nonConstVersion = f.getNonConst();
nonConstVersion.doStuff();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment