简体   繁体   中英

Can alloca () be replacement for auto pointers in C++?

alloca () is used to allocate memory from stack which is automatically freed on reaching the end of the scope. At the same time, auto pointers in C++ ensures the dynamically allocated memory from heap is automatically freed during stack winding.

Would it be right to say that alloca() provides similar functionality of automatic reclaim as provided by auto pointers?

No, not at all, that would be entirely wrong. The purpose of smart pointers in C++ ( unique_ptr , shared_ptr and the old and deprecated auto_ptr ) is to own allocations of memory on the free store, ie objects allocated with new (though there's some flexibility). The vendor-specific alloca allocates memory (not objects) on the call stack, not on the free store.

The closest analogue for alloca in a standard is the variable-length array of C, but C++ doesn't even have that. And even then the semantics are different, since names in C and C++ are scoped, but the semantics of alloca are not systematically tied to scopes (but rather to functions ). If you will, think of alloca as providing "local variables of dynamic size", but that analogy has many pitfalls.

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