指向共享对象的指针在拥有它的不同对象中是不同的
a pointer to a shared object is different in different objects which owns it
我有一个共享指针到共享对象的问题。我在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));
如果你不使用指向对象的指针,它可能会复制该对象,然后运行线程
相关文章:
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 在C++中使用默认构造函数初始化对象的不同方法
- 使用默认构造函数初始化对象的不同方法
- 有没有办法在C++中循环访问对象的不同数据成员
- 删除对象(具有不同类型)的引用时会发生什么情况?
- 将一个向量映射到不同的对,即使向量映射到每对时是不同的?
- int* 和 int** 是不同的类型吗?C++
- 我如何知道COM对象与不同的COM UUIDS兼容
- C++问题,我的两个源代码应该具有相同的输出,但它们是不同的
- 通过 char* 缓冲区读取 int 的行为是不同的,无论是正数还是负数
- OpenSSL:读取EC密钥,然后再次写入,这是不同的
- 来自同一对象的不同指针值
- "const_iterator"真的需要与"迭代器"是不同的类吗?
- C++ 如果 Printf 位于函数中,则返回是不同的
- 如何设计对象以不同方式设置文本格式
- 在 c++ 中初始化对象的不同方法
- 在C 字符串中,为什么在最后一个字符之后,通过索引和()访问索引时行为是不同的
- 我正在比较两个具有相同值的变量,但它说它们是不同的
- 为什么我班的人数是零?如何确保不同的对象具有不同的地址
- 指向共享对象的指针在拥有它的不同对象中是不同的