我读过了 即使对象是共享所有权的副本,多个线程也可以同时读写不同的shared_ptr对象。 ( MSDN:标准C ++库中的线程安全 ) 这是否意味着更改shared_ptr对象是安全的? 例如,下一个代码是否被认为是安全的: shared_ptr<myClass> global = make_shared<myClass>(); … //In thread 1 shared_ptr<myClass> private = global; … //In thread 2 global = make_shared<myClass>(); … 我可以肯定,在这种情况下,线程1 private将具有global的原始值或线程2分配的新值,但无论哪种方式将有一个有效的shared_ptr myClass? == ==编辑 只是为了解释我的动机。 我想有一个共享的指针来保存我的configuration,我有一个线程池来处理请求。 所以global是全球configuration。 thread 1正在采取当前configuration,因为它开始处理请求。 thread 2正在更新configuration。 (只适用于未来的请求) 如果工作的话,我可以在不中断请求处理的情况下更新configuration。
如果我有一个需要使用shared_ptr的函数,将它的引用传递给它是不是更有效率(所以为了避免复制shared_ptr对象)? 什么是可能的不良副作用? 我设想了两种可能的情况: 1)里面的函数副本是由参数,如在 ClassA::take_copy_of_sp(boost::shared_ptr<foo> &sp) { … m_sp_member=sp; //This will copy the object, incrementing refcount … } 2)里面的函数只是使用参数,就像 Class::only_work_with_sp(boost::shared_ptr<foo> &sp) //Again, no copy here { … sp->do_something(); … } 在这两种情况下,我都看不到通过值而不是引用传递boost::shared_ptr<foo>的好理由。 按值传递只会“暂时”增加由于复制引起的引用计数,然后在退出函数范围时将其递减。 我可以俯视吗? 为了澄清,在阅读了几个答案之后,我完全赞同过早优化的问题,而且我总是试图首先在那个热点上工作。 如果你明白我的意思,我的问题更多的来自纯技术的代码观点。
当一个函数需要一个shared_ptr (来自boost或C ++ 11 STL)时,你是否传递它 通过const引用: void foo(const shared_ptr<T>& p) 或值: void foo(shared_ptr<T> p) ? 我宁愿第一种方法,因为我怀疑它会更快。 但是,这真的值得吗?还是还有其他问题? 请给出你select的理由或者如果是这样的话,为什么你认为这没有关系。
我开始研究C ++ 11的智能指针,我没有看到任何有用的std::weak_ptr 。 有人可以告诉我什么时候std::weak_ptr是有用的/必要的?
我发现一些代码使用std :: shared_ptr在关机时执行任意清理。 起初我以为这个代码不可能工作,但后来我尝试了以下几点: #include <memory> #include <iostream> #include <vector> class test { public: test() { std::cout << "Test created" << std::endl; } ~test() { std::cout << "Test destroyed" << std::endl; } }; int main() { std::cout << "At begin of main.\ncreating std::vector<std::shared_ptr<void>>" << std::endl; std::vector<std::shared_ptr<void>> v; { std::cout << "Creating test" << std::endl; v.push_back( […]
该标准提供了std::unique_ptr的模板专门化,它从析构函数中正确地调用了delete[] : void func() { std::unique_ptr< int[] > arr(new int[10]); ……. } 使用std::shared_ptr这个专门化是不可用的,所以有必要提供一个正确调用delete[] : void func() { // Usage shared_ptr array (new double [256], [](double* arr) { delete [] arr; } ); ………….. } 这只是一个疏忽吗? (以同样的方式,有一个std::copy_if )或有一个原因?
我有这个代码不起作用,但我认为这个意图很明显: testmakeshared.cpp #include <memory> class A { public: static ::std::shared_ptr<A> create() { return ::std::make_shared<A>(); } protected: A() {} A(const A &) = delete; const A &operator =(const A &) = delete; }; ::std::shared_ptr<A> foo() { return A::create(); } 但是当我编译它时,我得到这个错误: g++ -std=c++0x -march=native -mtune=native -O3 -Wall testmakeshared.cpp In file included from /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr.h:52:0, from /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/memory:86, from testmakeshared.cpp:1: […]
只是一个关于shared_ptr的小查询。 使用shared_ptr指向数组是否是一个好习惯? 例如, shared_ptr<int> sp(new int[10]); 如果没有,那为什么不呢? 我已经知道的一个原因是不能递增/递减shared_ptr 。 因此,它不能像正常的数组指针一样使用。