intrusive_ptr in c++11

Does c++11 have something equivalent to boost::intrusive_ptr? No. It does have std::make_shared which means std::shared_ptr is almost (see note below) as efficient as an intrusive smart pointer, because the reference counts will be stored adjacent in memory to the object itself, improving locality of reference and cache usage. It also provides std::enable_shared_from_this which allows you …

Read more

Why does unique_ptr instantiation compile to larger binary than raw pointer?

Because std::make_unique<int[]>(100) performs value initialization while new int[100] performs default initialization – In the first case, elements are 0-initialized (for int), while in the second case elements are left uninitialized. Try: int *p = new int[100](); And you’ll get the same output as with the std::unique_ptr. See this for instance, which states that std::make_unique<int[]>(100) is …

Read more

How can you efficiently check whether two std::weak_ptr pointers are pointing to the same object?

Completely rewriting this answer because I totally misunderstood. This is a tricky thing to get right! The usual implementation of std::weak_ptr and std::shared_ptr that is consistent with the standard is to have two heap objects: the managed object, and a control block. Each shared pointer that refers to the same object contains a pointer to …

Read more

Can you make a std::shared_ptr manage an array allocated with new T[]?

With C++17, shared_ptr can be used to manage a dynamically allocated array. The shared_ptr template argument in this case must be T[N] or T[]. So you may write shared_ptr<int[]> sp(new int[10]); From n4659, [util.smartptr.shared.const] template<class Y> explicit shared_ptr(Y* p); Requires: Y shall be a complete type. The expression delete[] p, when T is an array …

Read more

How to assign the address of an existing object to a smart pointer?

Try std::unique_ptr::reset void foo(bar &object){ std::unique_ptr<bar> pointer; pointer.reset(&object); } But be aware this is not recommended, you should not create a unique_ptr to a reference that is being passed to a function. At the end of the function, when pointer is being destroyed it will try to destroy object as well, and it won’t be …

Read more