auto_ptr的数组 [英] auto_ptr for arrays

查看:137
本文介绍了auto_ptr的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总之,我想知道如果有喜欢的类型数组一个auto_ptr。我知道我可以推出自己的,我只是确保有是不是已经出来的东西在那里。

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.

我是知道的载体为好。然而,我不认为我可以使用它们。我使用几个的Windows API的/软件开发工具包,如Windows媒体SDK,直接显示API,它为了找回一些结构来调用一个函数,它接受一个指针和大小的两倍。在第一时间传递NULL作为指针回去,我要以收到我寻找的数据分配的结构的大小。例如:

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;

由于cbType通常来自比的sizeof(WM_MEDIA_TYPE)回到更大,由于事实是有一个指向它的另一个结构,我不能只分配WM_MEDIA_TYPE对象。有没有这样的事了吗?

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?

推荐答案

使用

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

或从 C ++ 11

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

代替。

其他:
如果有人问,如果<一个href=\"http://herbsutter.word$p$pss.com/2008/04/07/cringe-not-vectors-are-guaranteed-to-be-contiguous/\">Vectors保证是连续答案是,因为C ++标准03。还有另一种<一个href=\"http://stackoverflow.com/questions/849168/are-stdvector-elements-guaranteed-to-be-continguous\">thread已经讨论过了。

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.

如果 C ++ 11 是由你的编译器支持,可以的unique_ptr用于数组。

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();

这篇关于auto_ptr的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆