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

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

本文关键字:对象 是不同 共享 指针 拥有      更新时间:2023-10-16

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

With 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;
  }
}

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

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