As I understand it, a std::weak_ptr is used as a safe way of referencing memory referenced by a std::shared_ptr which may have been deallocated. Can it be used with a std::unique_ptr as well?
As I understand it std::weak_ptr is used as a safe way of referencing memory referenced by shared_ptrs which may have been deallocated.
You understand wrong. std::weak_ptr allowes to access object, which ownership is maintained by std::shared_ptr without sharing it. Now when you really understand what std::weak_ptr does you should understand that your question about std::unique_ptr does not make any sense.
There is an equivalent pointer that act as an observer to a std::unique_ptr, but will not provide safety in the same way as std::weak_ptr.
That pointer is the raw pointer. They are safe to use if they don't outlive the unique owner.
If you need to know if the lifetime of the owner of a raw pointer ended, then no, there is no way and it's not the goal of std::unique_ptr.
Nope.
Unfortunately you will have to use std::shared_ptr, and document that the std::weak_ptrs should only be locked temporarily.
No.
The only constructors available to a weak_ptr are one that take either a shared_ptr or another weak_ptr.
http://en.cppreference.com/w/cpp/memory/weak_ptr/weak_ptr
Related
Question: Are there any compelling reasons to use naked pointers for non-owning resources or should we be using weak_ptr?
CPP.reference states
std::weak_ptr models temporary ownership: when an object needs to be accessed only if it exists, and it may be deleted at any time by someone else
But then, in the accepted answer for Which kind of pointer do I use when? we have the statement:
Use dumb pointers (raw pointers) or references for non-owning references to resources and when you know that the resource will outlive the referencing object / scope. Prefer references and use raw pointers when you need either nullability or resettability.... If you want a non-owning reference to a resource, but you don't know if the resource will outlive the object that references it, pack the resource in a shared_ptr and use a weak_ptr.
This answer is followed by a lot of back-and-forth about the use of naked pointers, with no real resolution. I can't see any reason for using dumb pointers. Am I missing something?
A weak_ptr has a very specific purpose: to break shared_ptr cycles. As an example, std::enable_shared_from_this is based on letting an object contain a weak_ptr to itself. If it directly contained a shared_ptr then that would create a cycle, so instead it has a weak_ptr.
You use a weak_ptr where you would otherwise have had a shared_ptr. The weak_ptr has a higher cost because in addition to the costs of shared_ptr there is the object existence checking that produces a shared_ptr, or not. Also it's a more complex beast so that it's easier to use incorrectly.
I can't think of any way that weak_ptr has anything to do with “temporary ownership” (except that after checking of existence and using a produced shared_ptr, that's one temporary shared ownership, which is repeated again and again for each use). For example, std::enable_shared_from_this has nothing to do with temporary ownership. Ordinarily I would just ignore a source of such a claim, and advice others to ignore it, but cppreference.com is about the best we have in the way of a free online C++ reference. It's odd that it contains a nonsense statement. But, nothing's prefect, as I once remarked to Bjarne in clc++, whereupon he corrected my speling of “prefect”. Hm! Well.
I don't know of any advantage in using a raw pointer rather than a weak_ptr, where a weak_ptr is what's required. A raw pointer can't do a weak_ptr's job of holding on to a shared_ptr's control block, so it seems to me that the mere idea of replacing a weak_ptr with a raw pointer is nonsense. But then, the day one stops being surprised by learning things one could never have thought of, is the day one is dead, and so it may be the case that there is some obscure-to-me such use.
Also, there is no advantage in using a weak_ptr where a raw pointer is what's required. Rather, the weak_ptr introduces a relatively speaking enormous cost, of control block allocation and reference counting. So I can't think of any situation where it would make sense to replace raw pointers with weak_ptr, and I don't expect this to be a case where I learn otherwise.
a weak pointer actually has very little usage. A weak pointer is only useful, if you need it's lock function (transform the pointer into a shared pointer, to prevent garbage collection while you are operating on it). Non owning pointers best, if you just use raw pointer, because of the overhead shared and weak pointer have.
I have a class A which has a field of type std::unique_ptr:
class A
{
public:
std::unique_ptr pointer;
// class body
};
And somewhere in code, I'm using few std::shared_ptrs which point to the same object. Now what I'd like to achieve is to move ownership to this std::unique_ptr in my class, so that if all shared_ptrs will be destroyed, my object will stay alive as long as this unique_ptr will stay alive.
My question is - is it possible to move ownership from std::shared_ptr to std::unique_ptr and if yes, how can I do this?
Logically such a scenario doesn't make sense to me.
Suppose for a while that it is possible to transfer the ownership, but you could do that only when you're sure that there is only one shared_ptr alives; if that is the case, then you can still use shared_ptr as member of A and pretend that it is unique_ptr.
And then you commented:
That's true, I could create shared_ptr in A class. I think I misunderstood a concept a bit again. I wanted to behave it in this way: if unique_ptr dies, the object itself dies too, even though shared_ptrs still point to it, but that's silly as they wouldn't know that object itself was destroyed and therefore they wouldn't be nullptrs.
In that case, you're looking at the wrong smart pointer. What you probably need is called std::weak_ptr. If so, then make sure you use one std::shared_ptr and all others as std::weak_ptr.
I have some questions about smart pointers implemented in boost library.
Is the only diffrence between shared_ptr and scoped_ptr that scoped_ptr doesn't have copy constructor and shared_ptr has it?
Should i use then scoped_ptr instead of shared_ptr always when object doesn't call copy constructor?
I also doesn't understand idea of shared/scoped array. Can't I just use std::vector instead of it?
Is the only diffrence between shared_ptr and scoped_ptr that
scoped_ptr doesn't have copy constructor and shared_ptr has it?
The difference is more fundamental than that; it has to do with how the smart pointers own the object it points to. What makes smart pointers different from dumb pointers is that the concept of ownership is a core component of their function. The ownership semantics is what differentiates the different kinds of smart pointers.
Because smart pointers "own" the thing they point to, they can do useful things like deleting objects when the smart pointers go away (this is made possible using only the rules of the language; no compiler magic is needed). This way, memory management can be made almost automatic in C++ (despite claims to the contrary, there's very little manual memory management required in modern C++).
shared_ptr implements reference-counting
semantics for
memory management. Multiple shared_ptrs can own a single object. A
shared_ptr going away does not necessarily delete the object it
points to because there may be another shared_ptr owning the
object. The last shared_ptr that owns an object and goes away will
delete the object it owns.
scoped_ptr implements exclusive-ownership semantics. Only one
scoped_ptr can own any one object. When a scoped_ptr goes away,
it will always delete the object it owns (because there's only one
owner). It's typically used as a lightweight RAII mechanism for
objects allocated on the free store.
The array versions (shared_array and scoped_array) have essentially the same semantics, but are designed specifically for arrays e.g. they use delete[] instead of delete, implements the array subscript operator, etc.
shared_ptr and shared_array also allows you to specify a custom deleter, if the default delete behavior is not appropriate for the object. scoped_ptr and scoped_array do not have that ability, since they are quite lightweight compared to shared_ptr and shared_array.
In C++11, the newest and current version of C++, there's also a unique_ptr, which is just like scoped_ptr except that you can transfer the ownership of an object to another unique_ptr. In C++03, an older but more widely supported version of C++, there's auto_ptr which is equivalent to unique_ptr except it was easy to use it in an unsafe manner by accident (which is why it is deprecated in C++11).
Should i use then scoped_ptr instead of shared_ptr always when object
doesn't call copy constructor?
Which one you choose doesn't depend on the presence of the copy-constructor, since shared_ptr and scoped_ptr does not require the object to be copy-constructible. You pick the one depending on the required ownership semantics. If the object will have multiple owners, you use shared_ptr. If the object will only have one owner and the object's existence lasts only within a scope, use scoped_ptr (hence the name scoped_ptr).
I also doesn't understand idea of shared/scoped array. Can't I just
use std::vector instead of it?
std::vector does not implement reference-counting semantics like shared_array does. std::vector is more like scoped_array, but can be copied. When you copy a std::vector, you also copy all of the elements it contains. That's not the case for scoped_array. std::vector also has functions that allow you to manipulate and examine its contents (e.g. push_back, insert, erase, etc.), but is much more heavyweight than scoped_array.
Yes. scoped_ptr does not allow for copies while shared_ptr does. But this "simple" difference makes a world of impact on both the implementation and the usage of the smart pointer.
scoped_ptr is faster and lighter than shared_ptr because no reference counting is involved. shared_ptr will count the number of assignments and not delete the object until all references have expired/gone out of scope.
Now your question regarding vectors implies that you're actually not familiar with the the concept of dynamic allocation and the difference between that and static allocation on the static. You really should look into reading a primer on C(++) and look into the reasons for dynamic allocation and when you need it.
A vector stores a list of objects. A XXX_ptr stores a pointer to a (single) dynamically-allocated object. Apples and oranges.
If you allocate memory, you can put the newly created pointer in a scoped pointer, so that IF the malloc/noew fails, the memory will be freed. This is how I usally uses it, or if it's an object that needs to be allocated on the heap, but that I want to treat it as a stack object in terms of that it will only be alive until the end of the scope.
The shared pointer is if you want to pass the pointer around and allow the object to have multiple owners. Then none of the owners needs to take responibility of the object and they can all just stop using it and be sure that it will be freed correclty. (you don't wanna free an object that you know is used by someone else)
I'd say you're thinking about it the wrong way. The question isn't whether you do call the copy constructor -- it's whether you need to call the copy constructor. In other words, you should be deciding whether to use shared_ptr or scoped_ptr not based on reading your code but based on thinking about object ownership and what objects' lifetimes should be.
Say you have an object that you want to create on the heap, not on the stack, for whatever reason (maybe it's too big to be on the stack, maybe you might want to replace it with a different object at some point, maybe you want it to be initialized late) but its lifetime should never be longer than its containing scope. A common example of this is instance variables in a class: they should often be deleted when the object they are in is deleted. Then, you should use scoped_ptr.
But sometimes you don't know when an object will be safe to delete in advance. For instance, consider an object in a lookup table. You want to return it in response to lookups, but what happens when it's deleted -- could someone still be using the object who looked it up previously? In cases like this, you can use shared_ptr, which shares the objects ownership so that it only gets deleted when nobody has a copy of the pointer anymore.
So why does anyone ever use scoped_ptr instead of shared_ptr? First of all, knowing when the destructor gets called is one of the big advantages of non-memory-managed languages like C++. Maybe the destructor is expensive, or maybe it frees a resource; it's nice to know when these things happen. Also, with shared_ptr, there's the potential for memory leaks if you create a circular reference by accident.
In general, almost every pointer you have should be "owned" -- there should be a single place in your code that news and deletes it. scoped_ptr is great for this; when you want an owned object to be passed around to non-owners you can use a bare pointer. But if you absolutely need an object's ownership to be shared, use shared_ptr -- as long as you're careful to use it correctly!
As for scoped/shared arrays, you can certainly use std::vector, but arrays are cheaper and sometimes people want the performance benefit.
shared_ptr is very different from scoped_ptr. scoped_ptr (which is now standardized in C++11 as std::unique_ptr) is simply a RAII-style smart pointer which takes ownership of a resource and then deallocates the owned resource when the pointer goes out of scope.
A shared_ptr however, may share ownership of the resource with other instances of shared_ptr. The resource stays alive as long as one or more shared_ptr instances own it. This is an automatic memory-management technique, (a form of garbage-collection) known as reference counting. It basically provides the same effect as more advanced garbage collection algorithms, except unlike other garbage collection techniques, it doesn't handle circular references.
As for using std::vector versus boost::scoped_array, yeah - scoped_array doesn't really offer much of an advantage. However, boost::shared_array offers reference counting semantics, just like shared_ptr.
What makes smartpointers better than normal pointers?
They simplify the problem of resource management. Once you hold your resources within smart pointers they will release memory for you when they go out of scope applying RAII techniques.
This has two main advantages: code is safer (less prone to resource leaks) and programming is easier as you do not need to remember in each part of your code whether the resource you are holding must be manually released.
The principal advantage is that the memory pointed to by the smart pointer will be automatically deallocated when the pointer does out of scope. With regular pointers, you have to manage the memory yourself.
A raw pointer doesn't take ownership of the resource it points to. When the pointer goes out of scope, the object it pointed to is unaffected. Often, you want some kind of ownership semantics where, when the pointer goes out of scope, the object it points to should either be deleted, or at least be notified that there's one less pointer pointing to it.
That is what smart pointers do.
A shared_ptr implements reference-counting, so that when all pointers to an object are destroyed, the object gets deleted.
Others, like scoped_ptr or unique_ptr or auto_ptr implement various forms of exclusive ownership. When a scoped_ptr is destroyed, it deletes the object it points to.
Fewer memory leaks. Maybe Scott Meyers can make it clearer for you:
Effective C++
More Effective C++
Automatic reference counting and deallocation.
While agreeing with the other answers in practice, I'd just like to say that nothing makes smart pointers better in principle, unless they happen to be what works for your application. That is, if a smart pointer isn't needed, it isn't better.
If the smart pointer you're talking about is std::auto_ptr, it could well be substantially worse than a simple pointer. But that's not so much a smart pointers issue as a semantics of assignment issue.
That said, smart pointers very often are useful - even the dreaded auto_ptr - especially (as mentioned above) WRT exception safety.
Have a look at:
Smart Pointers
I make a lot of use of boost::scoped_ptr in my code and it is great but I'm currently working with software that uses shared_ptr all over the place and I'm wondering if I'm missing something.
AFAIK a shared_ptr is only useful if different threads are going to be accessing the same data and you don't know what order the threads are going to finish (with the shared_ptr ensuring that the object exists until the last thread has finished with it).
Are there other use cases?
Threads are irrelevant here. What's relevant is whether it's easy to specify a point at which the object is no longer of use.
Suppose several different objects want to use the same object. It might be a pack of data, or for input/output, or some geometric object, or whatever. You want the shared object to be deleted after all of the using objects are deleted, and not a clock cycle before. Rather than figure out which owning object is going to have the longest lifespan (and that can change if you change the program, or perhaps through user interaction), you can use a shared_ptr to force this behavior.
It doesn't matter whether the using objects are in the same or different threads. Objects can have unpredictable lifetimes even if they're all in the same thread.
AFAIK a shared_ptr is only useful if
different threads are going to be
accessing the same data
Well, it's for situations where multiple owners own the same object pointed to by the smart pointer. They may access the smart pointers from different threads, and shared_ptr is usable in that area too, but that's not the main point. If the last owner loses its reference to the object pointed to, the shared_ptr mechanism deletes the object.
You can use a scoped_ptr if all you want to have is a pointer that is deleted when the scope it's created in is left (either by exceptions, by a goto to a place outside, or by normal control flow or some other mechanism). If you use it like that, there is no need to change to shared_ptr.
The difference between scoped_ptr and shared_ptr (and auto_ptr) is mainly copy semantics.
scoped_ptr is for "Resource Allocation Is Initialization" and is not copyable (it cannot be shared with other instances and ownership cannot be transferred)
shared_ptr is for automatic reclamation of memory when shared between multiple parties
auto_ptr is copyable (and transfers ownership when assigned)
Another important difference between shared_ptr and scoped_ptr is that only shared_ptr work with weak_ptr. Weak pointers are used to break cycles of shared pointers, thereby avoiding memory leaks, but weak_ptr can be used for more than that.
Shared and weak pointers may be used to express the difference between owning and non-owning references. Unambiguous ownership of data leads to a cleaner design, so when possible data objects should be owned by one other object through a shared_ptr. All other long-lived references to data objects should be weak pointers, expressing their non-ownership of the data. Each time any non-owning modules access the data, they need to convert the weak_ptr into a shared_ptr, at which point they may find that the data object no longer exists. However, while the non-owning modules access the data object, they hold it through transient shared_ptr, ensuring safe operation even if the owning object were to release the data.
As answered already, shared_ptr is about shared ownership. However, I would argue that shared ownership is generally a bad thing (exceptions exists, such as flyweight pattern) and it is better to identify an owner and put a scoped_ptr there.
A shared_ptr is a smart pointer type that does reference counting. If there's only one owner for the object (frequent case), then scoped_ptr is the right solution. If the object can be shared among multiple parts of the code, then shared_ptr won't let the object be destructed until all references to it have been released.