Using auto_ptr<> with array

喜你入骨 提交于 2019-12-10 00:54:58

问题


I'm using auto_ptr<> which uses an array of class pointer type so how do I assign a value to it.

e.g. auto_ptr<class*> arr[10];

How can I assign a value to the arr array?


回答1:


You cannot use auto_ptr with array, because it calls delete p, not delete [] p.

You want boost::scoped_array or some other boost::smart_array :)




回答2:


If you have C++0x (e.g. MSVC10, GCC >= 4.3), I'd strongly advise to use either a std::vector<T> or a std::array<T, n> as your base object type (depending on whether the size is fixed or variable), and if you allocate this guy on the heap and need to pass it around, put it in a std::shared_ptr:

typedef std::array<T, n> mybox_t;
typedef std::shared_ptr<mybox_t> mybox_p;

mybox_p makeBox() { auto bp = std::make_shared<mybox_t>(...); ...; return bp; }



回答3:


Arrays and auto_ptr<> don't mix.

From the GotW site:

Every delete must match the form of its new. If you use single-object new, you must use single-object delete; if you use the array form of new, you must use the array form of delete. Doing otherwise yields undefined behaviour.

I'm not going to copy the GotW site verbatim; however, I will summarize your options to solve your problem:

  1. Roll your own auto array

    1a. Derive from auto_ptr. Few advantages, too difficult.

    1b. Clone auto_ptr code. Easy to implement, no significant space/overhead. Hard to maintain.

  2. Use the Adapter Pattern. Easy to implement, hard to use, maintain, understand. Takes more time / overhead.
  3. Replace auto_ptr With Hand-Coded EH Logic. Easy to use, no significant space/time/overhead. Hard to implement, read, brittle.
  4. Use a vector<> Instead Of an Array. Easy to implement, easy to read, less brittle, no significant space, time, overhead. Syntactic changes needed and sometimes usability changes.

So the bottom line is to use a vector<> instead of C-style arrays.




回答4:


As everyone said here, don't mix arrays with auto_ptr. This must be used only when you've multiple returns where you feel really difficult to release memory, or when you get an allocated pointer from somewhere else and you've the responsibility to clean it up before existing the function.

the other thing is that, in the destructor of auto_ptr it calls delete operator with the stored pointer. Now what you're passing is a single element of an array. Memory manager will try to find and free up the memory blocks allocated starting from the address you're passing. Probably this might not be existing heap where all allocations are maintained. You may experience an undefined behavior like crash, memory corruption etc. upon this operation.



来源:https://stackoverflow.com/questions/6520844/using-auto-ptr-with-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!