【问题标题】:C++ Private mutex accessC++ 私有互斥访问
【发布时间】:2016-07-08 22:27:17
【问题描述】:

在 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.

(在我的版本中,这是清单 3.5)

为什么我可以直接访问其他对象的私有数据(在这种情况下为互斥体 m)? 也许我错过了什么,或者这是一个错字(我有这本书的俄文版本,没有勘误表)

提前致谢。

德米特里。

【问题讨论】:

  • 没什么特别的,你可以从同一个类的其他实例访问private成员。
  • @πάνταῥεῖ 说了什么。实例可以访问同一的其他实例中的私有数据。如果您考虑一下 - 这是复制构造函数可以工作的唯一方法(更不用说operator= 等)。

标签: c++ multithreading class private


【解决方案1】:

这是完全正常的,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.
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-27
  • 1970-01-01
  • 1970-01-01
  • 2011-08-05
  • 1970-01-01
相关资源
最近更新 更多