4 ms·
This way to call a function smells wrong anyway. A shared pointer to a new value is nonsense as a parameter, because at the point of the call the pointer is not
by jeffbee 5y ago
This way to call a function smells wrong anyway. A shared pointer to a new value is nonsense as a parameter, because at the point of the call the pointer is not shared, it is unique! Since a shared pointer is implicitly constructible from a unique pointer, this makes more sense, assuming there are other call sites that really intend to share ownership:
void frob(std::shared_ptr<T>);
main() {
frob(std::make_unique<T>());
}
- Koshkin 5y agoWell, usually you designate a pointer as 'shared' not only when it happens to be already shared but also when it will be shared later on.
- ot 5y agoIf you know that the pointer is going to be shared, it's more efficient to use `make_shared` as it will use a single allocation for both the object and the control block.
- Kranar 5y agoYou've now forgone an important optimization opportunity for absolutely no benefit.
- dzdt 5y agoThere is a mental optimization to be had by using only a subset of the language. If you can get by using fewer constructs (and work on code with like-minded authors) you can better learn to use them correctly and save on thought as to which is the most optimal approach in every case.
- Kranar 5y agoGreat, so stick to the subset of providing a function that asks for a shared_ptr with a shared_ptr instead of introducing unique_ptr as an additional construct. This way you get the benefits of the optimization and don't need to add the overhead of thinking about how shared_ptr will take a unique_ptr and perform a conversion on it. If something takes a foo, give it a foo.