Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

c++ - How to pass deleter to make_shared?

Since C++11, because of several reasons, developers tend to use smart pointer classes for dynamic lifetime objects. And with those new smart pointer classes, standards, even suggest to not use operators like new instead they suggest to use make_shared or make_unique to avoid some error prone.

If we like to use a smart pointer class, like shared_ptr, we can construct one like,

shared_ptr<int> p(new int(12));

Also we would like to pass a custom deleter to smart pointer classes,

shared_ptr<int> p(new int(12), deleter);

On the other hand, if we like to use make_shared to allocate, for ex. int, instead of use new and shared_ptr constructor, like on the first expression above, we can use

auto ip = make_shared<int>(12);

But what if we like to also pass a custom deleter to make_shared, is there a right way to do that? Seems like compilers, at least gcc, gives an error to,

auto ip = make_shared<int>(12, deleter);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As other have said, make_shared cannot be used with a custom deleter. But I want to explain why.

Custom deleters exist because you allocated the pointer in some special way, and therefore you need to be able to deallocate it in a correspondingly special way. Well, make_shared allocates the pointer with new. Objects allocated with new should be deallocated with delete. Which the standard deleter dutifully does.

In short, if you can live with the default allocation behavior, you can live with the default deallocation behavior too. And if you can't live with the default allocation behavior, you should use allocate_shared, which uses the provided allocator to both allocate and deallocate the storage.

Also, make_shared is allowed to (and almost certainly will) allocate the memory for T and the control block for the shared_ptr within the same allocation. This is something that your deleter can't really know about or deal with. Whereas allocate_shared is capable of handling it, since the allocator you provide can do allocation and deallocation duties.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...