拥有这样的代码是个好主意: 任何陷阱? 使用共享此指针是一种更好的设计吗?
class X {
public:
void foo();
void bar2(const boost::weak_ptr<X>& x);
};
void X::foo() {}
void X::bar2(const boost::weak_ptr<X>& x) {}
void foo()
{
const boost::shared_ptr<X> x = boost::make_shared<X>();
boost::weak_ptr<X> weakX(x);
x->bar2(weakX);
}
int
main()
{
foo();
return 0;
}
答案 0 :(得分:0)
如果传入函数的参数应该始终是threads = []
max_threads = 10
loop do
begin
threads << Thread.new do
helper_method(1,2,3,4)
end
rescue Exception => e
puts "Error Starting thread"
end
begin
threads = threads.select { |t| t.alive? ? true : (t.join; false) }
while threads.size >= max_threads
puts 'Got Maximum threads'
sleep 1
threads = threads.select { |t| t.alive? ? true : (t.join; false) }
end
rescue Exception => e
puts e
end
end
- 这个版本你有问题。代码中没有任何内容强制执行此行为,因此您的类的用户可以轻松地将weak_ptr传递给weak_ptr
的另一个对象。
如果您需要class X
能够将bar2
传递给shared_ptr
,那么更好的解决方案是使用this
示例强>
std::enable_shared_from_this
<强>输出:强>
#include <iostream>
#include <memory>
struct Foo : public std::enable_shared_from_this<Foo> {
Foo() { std::cout << "Foo::Foo\n"; }
~Foo() { std::cout << "Foo::~Foo\n"; }
std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
};
int main() {
Foo *f = new Foo;
std::shared_ptr<Foo> pf1;
{
std::shared_ptr<Foo> pf2(f);
pf1 = pf2->getFoo(); // shares ownership of object with pf2
}
std::cout << "pf2 is gone\n";
}
来自http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/shared_from_this