Reputation: 3171
I have the following code and line 2 gives me an error during compilation. Is it possible to create a map of scoped pointers or do I have to use shared pointers instead?
map<int, scoped_ptr> mp;
mp[1] = scoped_ptr(new obj());
error:
boost::scoped_ptr<T>& boost::scoped_ptr<T>::operator=(const boost::scoped_ptr<T>&) [with T = ]’ is private
Upvotes: 3
Views: 774
Reputation: 1775
boost::scoped_ptr
is non-copyable, but you still can swap it.
Here is a trick :
// Example program
#include <iostream>
#include <string>
#include <map>
#include <boost/scoped_ptr.hpp>
int main()
{
std::map<int, boost::scoped_ptr<int>> myMap;
int * test = new int();
*test = 589;
boost::scoped_ptr<int> myScoped(test);
boost::swap(myMap[1], myScoped);
std::cout << *myMap[1];
}
Gives :
589
See on C++ Shell : http://cpp.sh/3zm3
However, I advise you not to do it.
Upvotes: 0
Reputation: 29966
You can't, boost::scoped_ptr
is non-copyable by design (emphasis mine):
The scoped_ptr template is a simple solution for simple needs. It supplies a basic "resource acquisition is initialization" facility, without shared-ownership or transfer-of-ownership semantics. Both its name and enforcement of semantics (by being noncopyable) signal its intent to retain ownership solely within the current scope.
<...>
scoped_ptr cannot be used in C++ Standard Library containers. Use shared_ptr if you need a smart pointer that can.
You can, however, emplace shared_ptr
s into a container, since in this case no copying is performed:
std::list<boost::scoped_ptr<MyClass>> list;
list.emplace_back(new MyClass());
Upvotes: 1