Creating an object and giving ownership to a container using a unique_ptr is no problem. How would one remove an element by raw pointer?
std::set<std::unique_ptr<MyClass>> mySet;
MyClass *myClass = new MyClass();
mySet.insert(std::unique_ptr<MyClass>(myClass));
// remove myClass from mySet?
You will need to find the iterator corresponding to the myClass element and then pass that iterator to mySet.erase(). The iterator may be found using the std::find_if algorithm with a custom Predicate functor that understands how to dereference unique_ptr and compare it to the raw pointer myClass.
You can not use the overloaded size_t set::erase ( const key_type& x ); since the raw pointer (even if wrapped in a temporary unique_ptr) will not be found in mySet.
Not as pretty as I would've liked. But the following does the job:
#include <memory>
#include <set>
#include <iostream>
struct do_nothing
{
void operator()(const void*) const {}
};
struct MyClass
{
MyClass() {std::cout << "MyClass()\n";}
MyClass(const MyClass&) {std::cout << "MyClass(const MyClass&)\n";}
~MyClass() {std::cout << "~MyClass()\n";}
};
int main()
{
std::set<std::unique_ptr<MyClass>> mySet;
MyClass *myClass = new MyClass();
mySet.insert(std::unique_ptr<MyClass>(myClass));
// remove myClass from mySet?
std::set<std::unique_ptr<MyClass>>::iterator i =
lower_bound(mySet.begin(), mySet.end(),
std::unique_ptr<MyClass, do_nothing>(myClass));
if (i != mySet.end() && *i == std::unique_ptr<MyClass, do_nothing>(myClass))
mySet.erase(i);
}
It seems i am able to retrieve an iterator using a custom Predicate with lower_bound. Since std::set is an ordered container, lower_bound should perform logarithmically.
std::set<std::unique_ptr<MyClass>>::iterator i =
std::lower_bound(mySet.begin(), mySet.end(), myClass, MyPredicate<MyClass>());
template<class Type>
struct MyPredicate
{
bool operator()(const std::unique_ptr<Type>& left, const Type* right) const
{
return left.get() < right;
}
}
Still not the best solution but for the moment i go with:
PointerMap<MyFoo>::Type myFoos;
MyFoo * myFoo = new MyFoo();
myFoos.insert(PointerMap<MyFoo>::Item(myFoo));
The header is:
#include <map>
#include <memory>
#include <utility>
template<typename T>
struct PointerMap
{
typedef std::map<T *, std::unique_ptr<T>> Type;
struct Item : std::pair<T *, std::unique_ptr<T>>
{
Item(T * pointer)
: std::pair<T *, std::unique_ptr<T>>(pointer, std::unique_ptr<T>(pointer))
{
}
};
};
You might like the answer over here: Efficiently erase a unique_ptr from an unordered_set
That's for C++14, but I think applies to C++11 as well.
It is not pretty, but does the efficient thing — no scanning the container, but using proper hash-based lookup.
Related
Is there a way to write a copy-constructor for a class (say, Copyable, that holds a std::unique_ptr to a Base class (but really is storing Derived objects.
A quick test shows the expected slicing occurs, because Copyable doesn't know the real type it's holding. So I suppose a clone method is needed, but I'm wondering if there is a way to let the compiler handle this in some better way?
The slicing code:
#include <algorithm>
#include <iostream>
#include <memory>
struct Base
{
Base(int i = 0) : i(i) {}
virtual ~Base() = default;
int i;
virtual int f() { return i; }
};
struct Derived : Base
{
Derived() = default;
virtual int f() override { return 42; }
};
struct Copyable
{
Copyable(std::unique_ptr<Base>&& base) : data(std::move(base)) {}
Copyable(const Copyable& other)
{
data = std::make_unique<Base>(*other.data);
}
std::unique_ptr<Base> data;
};
int main()
{
Copyable c(std::make_unique<Derived>());
Copyable c_copy = c;
std::cout << c_copy.data->f() << '\n';
}
The clone code:
#include <algorithm>
#include <iostream>
#include <memory>
struct Base
{
Base(int i = 0) : i(i) {}
virtual ~Base() = default;
int i;
virtual int f() { return i; }
virtual Base* clone() { return new Base(i); }
};
struct Derived : Base
{
Derived() = default;
virtual int f() override { return 42; }
virtual Derived* clone() override { return new Derived(); }
};
struct Copyable
{
Copyable(std::unique_ptr<Base>&& base) : data(std::move(base)) {}
Copyable(const Copyable& other)
{
data.reset(other.data->clone());
}
std::unique_ptr<Base> data;
};
int main()
{
Copyable c(std::make_unique<Derived>());
Copyable c_copy = c;
std::cout << c_copy.data->f() << '\n';
}
Obviously the clone code works. Thing is, there's some things in it I'd like to avoid:
raw new.
a random function that needs to be part of the interface.
This function returns a raw pointer.
Every user of this class that wants to be copyable needs to call this function.
So, is there a "clean" alternative?
Note I want to use smart pointers for all the obvious reasons, I just need a deep copying std::unique_ptr. Something like std::copyable_unique_ptr, combining optional move semantics with a deep copying copy constructor. Is this the cleanest way? Or does that only add the the confusion?
You can certainly create a clone_ptr-class for any object you know statically how to clone.
It would hold a pointer to the object, and a pointer to a function for cloning said object, probably from converting a stateless lambda.
I have a bunch of derived classes stored as shared pointers, I was wondering if there is any way of getting a weak_ptr to the object from inside the object?
I've tried using the shared_from_this() function but the problem is that since it's a derived class, when I make the base class inherit from enable_shared_from_this, when the derived class calls shared_from_this() it gets a shared_ptr of the base class not the derived class which I can't turn into a shared_ptr of the derived class
Any suggestions?
Usign CRTP you can achieve it:
#include <memory>
template<typename T>
struct B: std::enable_shared_from_this<T> {};
struct D: B<D> {};
int main() {
std::shared_ptr<B<D>> b = std::make_shared<D>();
std::shared_ptr<D> d = b->shared_from_this();
std::weak_ptr<D> w = b->shared_from_this();
}
If you want to have a common, non-template base class, you can rely on techniques like the double dispatching, as in the following example:
#include <memory>
#include <iostream>
struct D1;
struct D2;
struct S {
void doSomething(std::weak_ptr<D1> weak) { std::cout << "D1" << std::endl; }
void doSomething(std::weak_ptr<D2> weak) { std::cout << "D2" << std::endl; }
};
struct B: std::enable_shared_from_this<B> {
virtual void dispatch(S &) = 0;
};
template<typename T>
struct M: B {
void dispatch(S &s) override {
auto ptr = std::static_pointer_cast<T>(shared_from_this());
s.doSomething(ptr);
}
};
struct D1: M<D1> {};
struct D2: M<D2> {};
int main() {
std::shared_ptr<B> b = std::make_shared<D1>();
S s;
b->dispatch(s);
}
As #Torbjörn said, using the dynamic_pointer_cast<Derived>(base_ptr) fixed this problem as it allowed me to convert shared_ptr's down in inheritance, something that isn't directly allowed.
I was wondering about this. Consider this:
#include <iostream>
#include <map>
#include <memory>
int main() {
std::map< int, std::unique_ptr<int> > m =
{ { 1, std::unique_ptr<int>(new int(3)) } };
return(0);
}
This is C++11. It fails to compile with a long ream of error messages on GCC, including one
/usr/include/c++/4.9/ext/new_allocator.h:120:4: error: use of deleted function ‘constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const int; _T2 = std::unique_ptr<int>]’
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
Is it possible at all to do what I'm trying to do here? I note that with shared_ptr, it works OK. Is it possible to do it with unique_ptr? If so, what am I missing? If not, why not?
No.
The elements of an initializer_list cannot be modified.
The unique_ptr cannot be moved (because it's const) and it can't be copied (because it's a move-only type), so you're hosed.
Sure, no problem.
First, a smart unique_ptr proxy, so we can create and move them around in a const context:
template<class T>
struct il_up {
mutable std::unique_ptr<T> ptr;
template<class U,
std::enable_if_t< std::is_convertible<U*, T*>{}, int>* =nullptr
>
il_up( std::unique_ptr<U> o ): ptr(std::move(o)) {}
operator std::unique_ptr<T>() const {
return std::move(ptr);
}
};
We then want to store this in an initializer_list. Even though it is const, it can pass the unique_ptr out.
Then a container-making proxy to store the temporary initializer list:
template<class T>
struct make_container {
std::initializer_list<T> il;
make_container( std::initializer_list<T> const& l ):il(l) {} // const& here matters
template<class C>
operator C()&&{
return {il.begin(), il.end()};
}
};
and we are done:
std::vector<std::unique_ptr<int>> vec = make_container<il_up<int>>{
std::make_unique<int>(1), std::make_unique<int>(2),
std::make_unique<int>(3), std::make_unique<int>(4)
};
live example.
I'm not sure of the title, because I'm not sure the issue comes from the "copyablility" of my container.
I tryied quite everything but I can't get rid of this error.
Here is a simplified version of my code (please do not challenge the class design, I really would like to keep the end-used syntax in the BOOST_FOREACH):
template <typename T>
class MyContainer
{
public:
typedef typename std::vector<T>::iterator iterator;
typedef typename std::vector<T>::const_iterator const_iterator;
MyContainer(std::vector<T>& vec, boost::mutex& mutex) :
m_vector(vec),
m_lock(mutex)
{
}
iterator begin() { return m_vector.begin(); }
const_iterator begin() const { return m_vector.begin(); }
iterator end() { return m_vector.end(); }
const_iterator end() const { return m_vector.end(); }
private:
std::vector<T>& m_vector;
boost::lock_guard<boost::mutex> m_lock;
};
template <typename T>
struct GetContainer
{
GetContainer(std::vector<T>& vec, boost::mutex& mutex) :
m_vector(vec),
m_mutex(mutex)
{
}
MyContainer<T> Get()
{
return MyContainer<T>(m_vector, m_mutex);
}
std::vector<T>& m_vector;
boost::mutex& m_mutex;
};
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
boost::mutex m;
GetContainer<int> getter(v, m);
BOOST_FOREACH(int i, getter.Get())
{
std::cout << i << std::endl;
}
return 0;
}
The compiler complains about not having a copy constructor for MyContainer::MyContainer(const MyContainer&).
I also have :
error: no matching function for call to ‘MyContainer::MyContainer(boost::foreach_detail_::rvalue_probe >::value_type)’
I follow the extensibility tips:
http://www.boost.org/doc/libs/1_58_0/doc/html/foreach/extensibility.html#foreach.extensibility.making__literal_boost_foreach__literal__work_with_non_copyable_sequence_types
But, making
MyContainer<T> : private boost::noncopyable
doesn't solve the issue.
Nor defining the function
boost_foreach_is_noncopyable
or specializing the template struct
is_noncopyable
for MyContainer (in fact, how would I specialize this template for a template type ?)
Last "tip":
If I remove the mutex and the lock from everywhere (I just pass the vector to GetContainer and to MyContainer), it works.
But it doesn't work if I make
MyContainer<T> : private boost::noncopyable
(I expected it should, so I'm not sure my problem is with BOOST_FOREACH, but maybe because I return a copy of MyContainer with my getter ?)
I thank you if you read me until here, and thanks in advance for help.
Seems to be a limitation of BOOST_FOREACH with move-only types. I didn't find a way around it¹ (except for the - ugly - obvious approach to put the lock_guard in a shared_ptr).
You didn't specify a c++03 requirement, though, so you can make it work without BOOST_FOREACH by replacing lock_guard with unique_lock.
Here's my take on things in c++11 (note how generic it is):
Live On Coliru
#include <boost/thread.hpp>
#include <boost/range.hpp>
namespace detail {
template <typename R, typename M>
struct RangeLock {
RangeLock(R&r, M& m) : _r(r), _l(m) {}
RangeLock(RangeLock&&) = default;
using iterator = typename boost::range_iterator<R>::type;
iterator begin() { using std::begin; return begin(_r); }
iterator end () { using std::end; return end (_r); }
using const_iterator = typename boost::range_iterator<R const>::type;
const_iterator begin() const { using std::begin; return begin(_r); }
const_iterator end () const { using std::end; return end (_r); }
private:
R& _r;
boost::unique_lock<M> _l;
};
}
template <typename R, typename M>
detail::RangeLock<R,M> make_range_lock(R& r, M& mx) { return {r,mx}; }
template <typename R, typename M>
detail::RangeLock<R const,M> make_range_lock(R const& r, M& mx) { return {r,mx}; }
#include <vector>
#include <map>
int main() {
boost::mutex mx;
std::vector<int> const vec { 1, 2 };
std::map<int, std::string> const map { { 1, "one" }, { 2, "two" } };
for(int i : make_range_lock(vec, mx))
std::cout << i << std::endl;
for(auto& p : make_range_lock(map, mx))
std::cout << p.second << std::endl;
for(auto& p : make_range_lock(boost::make_iterator_range(map.equal_range(1)), mx))
std::cout << p.second << std::endl;
}
Prints
1
2
one
two
one
¹ not even using all the approaches from Using BOOST_FOREACH with a constant intrusive list
I post my answer if it can help...
With C++03, I finally provide a copy constructor to be able to use the class with BOOST_FOREACH.
So the issue is moved to another topic: make the class copied in a logic and suitable way.
In my case, I "share the lock and the vector", the user shouldn't use this copy itself if he doesn't want to do bugs, but in BOOST_FOREACH it's okay:
I change the mutex to a recursive_mutex
I change the lock to an unique_lock
and:
MyContainer(const MyContainer& other) :
m_vector(other.vec),
m_lock(*other.m_lock.mutex())
{
}
With C++11
Thanks to Chris Glover on the boost mailling list, a C++11 solution:
You can't do what you are trying to do in C++03. To accomplish it, you
need C++11 move semantics to be able to move the MyContainer out of the Get
function. Even without using BOOST_FOREACH, the following code fails;
GetContainer<int> getter(v, m);
MyContainer<int> c = getter.Get(); // <-- Error.
Here's an example with the necessary changes; I changed the scoped_lock to
a unique_lock and added a move constructor.
template <typename T>
class MyContainer
{
public:
[...]
MyContainer(MyContainer&& other)
: m_vector(other.m_vector)
{
m_lock = std::move(other.m_lock);
other.m_vector = nullptr;
}
I've been trying to figure out this problem for a couple days now and finally figured it out after striping everything down to the code below. You'll see in the code below three different attempts at a constructor for const_iterator, along with the errors I get on two of them. It appears to me that the compiler is trying to use std::iterator instead of the locally declared mine::iterator. Is it supposed to be that way?
Other tidbits that have given clues:
If I name mine::iterator something else, like mine::B, then const_iterator(const B &rhs) works.
If I derive const_iterator from a class other than std::iterator, then const_iterator(const iterator<T> &rhs) works.
Thanks for any info. Here's the code:
#include "stdafx.h"
#include <iterator>
namespace mine
{
template <class T>
class iterator : public std::iterator<std::random_access_iterator_tag, T, ptrdiff_t, T*, T&>
{
public:
iterator() {}
};
template <class T>
class const_iterator : public std::iterator<std::random_access_iterator_tag, T, ptrdiff_t, const T*, const T&>
{
public:
const_iterator() {}
const_iterator(const mine::iterator<T> &rhs) {} // works
//const_iterator(const iterator &rhs) {} // error C2440: initializing: cannot convert from 'mine::iterator<T>' to 'mine::const_iterator<T>'
//const_iterator(const iterator<T> &rhs) {} // error C2976: std::iterator: too few template arguments
};
}// namespace mine
using namespace mine;
int _tmain(int argc, _TCHAR* argv[])
{
iterator<int> y;
const_iterator<int> x = y;
return 0;
}
First of all 'using namespace' is evil, use typedef for ease of use. for example instead of saying iterator use mine::iterator.
Also your second point gives the answer of your question. "If I derive const_iterator from a class other than std::iterator, then const_iterator(const iterator<T> &rhs) works."
Here the nearest iterator belongs to std not mine, as std::iterator is the base class of your const_iterator.