指向共享对象的指针在拥有它的不同对象中是不同的

a pointer to a shared object is different in different objects which owns it

我在共享指向共享对象的指针时遇到问题。我在 class A 中有一个 C 类型的对象,它与 B 类型的对象共享一个指向它的指针。然后该对象有一个正在更改对象 c 的值 val 的线程,但更改不会应用于存储在对象 b 中的指针。任何人都可以帮助我为什么会这样?

BOOST:

#include <iostream>
#include <boost/thread.hpp>

class C {
public:
  C(int _val): val(_val) {

  }

  ~C(){

  }

  void live(){
    while (true){
      val = rand() % 1000;
      std::cout << "val = " << val << std::endl;
    }
  }

  void setVal(int a){

    val = a;
  }

  int getVal(){
    return val;
  }

private:
  int val;
};

class B {
public:
  B(C* _pointer){
    pointer = _pointer;
  }

  void live(){
    while (true);
  }

  ~B(){

  }

  C* pointer;
};

class A {
public:
  A(): c(10), b(&c) {

  }

  void init() {
    t0 = boost::thread(boost::bind(&B::live, b));
    t1 = boost::thread(boost::bind(&C::live, c));
  }

  ~A() {

  }

  boost::thread t0, t1;

  B b;
  C c;
};

void main() {
  A a;
  a.init();

  while (true){
    std::cout << a.b.pointer->getVal() << std::endl;
  }
}

C++ 11:

#include <iostream>
#include <thread>

class C {
public:
  C(int _val): val(_val) {

  }

  ~C(){

  }

  void live(){
    while (true){
      val = rand() % 1000;
      std::cout << "val = " << val << std::endl;
    }
  }

  void setVal(int a){

    val = a;
  }

  int getVal(){
    return val;
  }

private:
  int val;
};

class B {
public:
  B(C* _pointer){
    pointer = _pointer;
  }

  void live(){
    while (true);
  }

  ~B(){

  }

  C* pointer;
};

class A {
public:
  A(): c(10), b(&c) {

  }

  void init() {
    t0 = std::thread(std::bind(&B::live, b));
    t1 = std::thread(std::bind(&C::live, c));
  }

  ~A() {

  }

  std::thread t0, t1;

  B b;
  C c;
};

void main() {
  A a;
  a.init();

  while (true){
    std::cout << a.b.pointer->getVal() << std::endl;
  }
}

我更改了这段代码:

t0 = boost::thread(boost::bind(&B::live, b));
t1 = boost::thread(boost::bind(&C::live, c));

至:

t0 = boost::thread(std::bind(&B::live, &b));
t1 = boost::thread(std::bind(&C::live, &c));

如果您不使用指向对象的指针,它可能会复制该对象,然后 运行 线程。