在 Anthony Williams 的书“C++ Concurrency in Action: Practical Multithreading”中我找到了这个代码示例
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.
(在我的书中版本是 list 3.5)
为什么我可以直接访问其他对象私有(private)数据(在本例中为互斥量 m)? 也许我遗漏了什么或者这是一个错字(我有这本书的俄语版本并且没有勘误表)
提前致谢。
德米特里。
最佳答案
这是完全正常的,private
声明仅适用于子类和此类的使用,不适用于同一类的其他实例。事实上,这就是像 operator=
这样的东西的工作原理。
例如。
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.
}
关于C++ 专用互斥锁访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38276219/