Conversion from boost::shared_ptr to std::shared_ptr?

Based on janm’s response at first I did this: template<class T> std::shared_ptr<T> to_std(const boost::shared_ptr<T> &p) { return std::shared_ptr<T>(p.get(), [p](…) mutable { p.reset(); }); } template<class T> boost::shared_ptr<T> to_boost(const std::shared_ptr<T> &p) { return boost::shared_ptr<T>(p.get(), [p](…) mutable { p.reset(); }); } But then I realized I could do this instead: namespace { template<class SharedPointer> struct Holder { … Read more

How is std::tuple implemented?

One approach to implementing tuples is using multiple-inheritance. The tuple-elements are held by leaf-classes, and the tuple class itself inherits from multiple leafs. In pseudo-code: template<typename T0, typename T1, …, typename Tn> class PseudoTuple : TupleLeaf<0, T0>, TupleLeaf<1, T1>, …, TupleLeaf<n, Tn> { … }; Each leaf has an index, so that each base-class becomes … Read more

what does `using std::swap` inside the body of a class method implementation mean?

This mechanism is normally used in templated code, i.e. template <typename Value> class Foo. Now the question is which swap to use. std::swap<Value> will work, but it might not be ideal. There’s a good chance that there’s a better overload of swap for type Value, but in which namespace would that be? It’s almost certainly … Read more

C++ STL map: is access time O(1)?

The complexity of lookup for std::map is O(log N) (logarithmic in the size of the container). Per Paragraph 23.4.4.3/4 of the C++11 Standard on std::map::operator []: Complexity: logarithmic. The complexity of lookup for std::unordered_map is O(1) (constant) in the average case, and O(N) (linear) in the worst case. Per Paragraph 23.5.4.3/4 of the C++11 Standard … Read more

std::vector resize downward

Calling resize() with a smaller size has no effect on the capacity of a vector. It will not free memory. The standard idiom for freeing memory from a vector is to swap() it with an empty temporary vector: std::vector<T>().swap(vec);. If you want to resize downwards you’d need to copy from your original vector into a … Read more