Reputation: 85
In book "C++ Concurrency in Action: Practical Multithreading" by Anthony Williams I found this code example
template<typename T>
class threadsafe_stack
{
private:
std::stack<T> data;
mutable std::mutex m;
public:
threadsafe_stack(){}
threadsafe_stack (const threadsafe_stack& other)
{
std::lock_guard<<std::mutex> lock(other.m);
... rest of the code.
(in my version of the book this is listing 3.5)
Why I have direct access to other object private data (mutex m in this case)? Maybe I missed something or maybe this is a typo (I have Russian version of the book and there is no errata)
Thanks in advance.
Dmitry.
Upvotes: 0
Views: 767
Reputation: 33854
This is perfectly normal, the private
declaration only pertains to child classes and uses of this class, not to other instances of the same class. In fact this is how things like operator=
work.
eg.
class A {
private:
int b;
public:
A() : b(rand()) {}
A& operator=(const A& rhs) {
b = rhs.b;
}
};
class B : public A {
public:
void set(int newB) {
b = newB; // Not ok.
}
};
int main() {
A a, aa;
a.b = 5; // Not ok.
a = aa; // Ok.
}
Upvotes: 1