简体   繁体   中英

Why is auto_ptr specialized for void?

I have decided to move over from raw pointers to smart pointers, so I though I could start by reading http://en.cppreference.com/w/cpp/memory/auto_ptr .

There I've seen that they are specialized for void .

Why is this? Is it useful in any situation?

This was done in LWG 541 . The issue has the complete rationale. But in short it was done for compatibility with what was then std::tr1::shared_ptr (later standardized to std::shared_ptr ).

If you are investigating moving from raw pointers to smart pointers I strongly recommend you use unique_ptr in favor of auto_ptr . auto_ptr is deprecated, and for good reason. unique_ptr is the recommended replacement for auto_ptr .

Here is a link explaining the rationale for deprecating auto_ptr , and replacing it with unique_ptr .

std::auto_ptr was deprecated since C++11. Consider to study other smart pointers like std::shared_ptr and unique_ptr instead.

The answer to your question is (As far I know): std::auto_ptr uses delete to release the memory of its internal raw-pointer, but deleting void* has no sense at all, because void is an incomplete type and can never be the type of an object. Yo have to cast void* to the corresponding type of the pointed data before deleting it. So this smart pointer provides an specialization for void which has less capabilities (Note that the reference says that the void specialization has no member functions).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM