Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto_ptr for arrays

In short, I am wondering if there is an auto_ptr like type for arrays. I know I could roll my own, I'm just making sure that there isn't already something out there.

I know about vectors as well. however I don't think I can use them. I am using several of the Windows APIs/SDKs such as the Windows Media SDK, Direct Show API which in order to get back some structures to call a function which takes a pointer and a size twice. The first time passing NULL as the pointer to get back the size of the structure that I have to allocated in order to receive the data I am looking for. For example:

CComQIPtr<IWMMediaProps> pProps(m_pStreamConfig); DWORD cbType = 0; WM_MEDIA_TYPE *pType = NULL;  hr = pProps->GetMediaType(NULL, &cbType); CHECK_HR(hr);  pType = (WM_MEDIA_TYPE*)new BYTE[cbType];   // Would like to use auto_ptr instread hr = pProps->GetMediaType(pType, &cbType); CHECK_HR(hr);  // ... do some stuff  delete[] pType; 

Since cbType typically comes back bigger than sizeof(WM_MEDIA_TYPE) due to the fact is has a pointer to another structure in it, I can't just allocate WM_MEDIA_TYPE objects. Is there anything like this out there?

like image 415
heavyd Avatar asked Jun 25 '09 16:06

heavyd


People also ask

Why auto_ptr is deprecated?

Why is auto_ptr deprecated? It takes ownership of the pointer in a way that no two pointers should contain the same object. Assignment transfers ownership and resets the rvalue auto pointer to a null pointer. Thus, they can't be used within STL containers due to the aforementioned inability to be copied.

Is auto_ptr deprecated?

The C++11 standard made auto_ptr deprecated, replacing it with the unique_ptr class template. auto_ptr was fully removed in C++17.

How is auto_ptr implemented?

The C++ standard provides class template auto_ptr in header file <memory> to deal with this situation. Our auto_ptr is a pointer that serves as owner of the object to which it refers. So, an object gets destroyed automatically when its auto_ptr gets destroyed.


2 Answers

Use

std::vector<BYTE> buffer(cbType); pType = (WM_MEDIA_TYPE*)&buffer[0]; 

or since C++11

std::vector<BYTE> buffer(cbType); pType = (WM_MEDIA_TYPE*)buffer.data(); 

instead.


Additional: If someone is asking if the Vectors are guaranteed to be contiguous the answer is Yes since C++ 03 standard. There is another thread that already discussed it.


If C++11 is supported by your compiler, unique_ptr can be used for arrays.

unique_ptr<BYTE[]> buffer(new BYTE[cbType]); pType = (WM_MEDIA_TYPE*)buffer.get(); 
like image 154
Totonga Avatar answered Oct 14 '22 14:10

Totonga


boost scoped_array or you can use boost scoped_ptr with a custom deleter

like image 24
Evan Teran Avatar answered Oct 14 '22 15:10

Evan Teran