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

时间:2015-06-06 17:45:55

标签: c++ boost boost-thread

我遇到共享指向共享对象的指针的问题。我在类C中有一个类型A的对象,它使用类型为B的对象共享指向它的指针。然后该对象有一个更改对象val的值c的线程,但更改不会应用于存储在对象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;
  }
}

1 个答案:

答案 0 :(得分:1)

我改变了这段代码:

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));

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