2016-11-18 103 views
-1

我有一个组中的所有指向相同的对象共享指针。在某个时刻,我希望这些指针离开第一个对象(应该被销毁),并且都开始指向另一个对象。我只能访问其中的一个指针,我不知道如何去做。如何更改由一组共享指针指向的对象?

一个例子:

using Ptr = shared_ptr<int>; 

void switch_all(Ptr &p) { 
    p.reset(new int(14)); 
} 

int main() { 
    Ptr a(new int(12)); 
    Ptr b = a; 
    Ptr c(a); 

    cout << "Initial situation: " << endl; 
    cout << *a.get() << '\t' << a.get() << endl; 
    cout << *b.get() << '\t' << b.get() << endl; 
    cout << *c.get() << '\t' << c.get() << endl; 

    switch_all(c); 

    cout << "After reset: " << endl; 
    cout << *a.get() << '\t' << a.get() << endl; 
    cout << *b.get() << '\t' << b.get() << endl; 
    cout << *c.get() << '\t' << c.get() << endl; 
} 

此输出

Initial situation: 
12  0xb8797038 
12  0xb8797038 
12  0xb8797038 
After reset: 
12  0xb8797038 
12  0xb8797038 
14  0xb8797468 

我想要做的是改变switch_all的方式,输出变为

Initial situation: 
12  0xb8797038 
12  0xb8797038 
12  0xb8797038 
After reset: 
14  0xb8797468 
14  0xb8797468 
14  0xb8797468 

这可能吗?怎么样?

回答

1

您无法重置由给定shared_ptr举行的指针,并有其他shared_ptr情况下自动拿起新指针。这根本不是如何shared_ptr的作品。当多个shared_ptr实例拥有相同的指针时,它们递增与该指针关联的引用计数。重置shared_ptr实例中的一个将简单地减少引用计数,其他shared_ptr实例与先前的指针保持一致,而复位shared_ptr现在保存新的指针。这是shared_ptr的全部要点,只要存在活动引用即可保持给定的指针处于活动状态。

你所要求的,需要额外的间接级别,例如:

using UPtr = unique_ptr<int>; 

void switch_all(UPtr &p) { 
    p.reset(new int(14)); 
} 

int main() { 
    UPtr a(new int(12)); 
    UPtr &b = a; 
    UPtr &c = a; 

    cout << "Initial situation: " << endl; 
    cout << *a.get() << '\t' << a.get() << endl; 
    cout << *b.get() << '\t' << b.get() << endl; 
    cout << *c.get() << '\t' << c.get() << endl; 

    switch_all(c); 

    cout << "After reset: " << endl; 
    cout << *a.get() << '\t' << a.get() << endl; 
    cout << *b.get() << '\t' << b.get() << endl; 
    cout << *c.get() << '\t' << c.get() << endl; 
} 

或者

using UPtr = unique_ptr<int>; 

void switch_all(UPtr *p) { 
    p->reset(new int(14)); 
} 

int main() { 
    UPtr a(new int(12)); 
    UPtr *b = &a; 
    UPtr *c = &a; 

    cout << "Initial situation: " << endl; 
    cout << *a.get() << '\t' << a.get() << endl; 
    cout << *(b->get()) << '\t' << b->get() << endl; 
    cout << *(c->get()) << '\t' << c->get() << endl; 

    switch_all(c); 

    cout << "After reset: " << endl; 
    cout << *a.get() << '\t' << a.get() << endl; 
    cout << *(b->get()) << '\t' << b->get() << endl; 
    cout << *(c->get()) << '\t' << c->get() << endl; 
} 
+0

我希望有一种方法来改变由管理对象存储的指针,所以所有指向该管理器对象的共享指针现在指向一个不同的管理对象。猜猜我必须从头开始设计一个shared_ptr类。 – user6245072