我有一个用例,每次都需要传递 boost::shared_array。如果缓冲区未完全使用,我想创建一个具有相同内存空间但从日期已写入的点开始的新指针
示例代码:
boost::shared_array<uint8_t> buffer;
boost::shared_array<uint8_t> placeHolder;
buffer.reset(new boost::uint8_t[1024 * 1024]);
placeHolder = buffer;
uint32_t maxSize = 1024 * 1024;
uint32_t dataCopied = 0;
while(dataCopied < 1024 * 1024)
{
uint32_t bytesWritten = getData(placeHolder, maxSize); //This call might give any size of data less than boost::shared_array<uint8_t> buffer;
placeHolder = boost::shared_array<uint8_t>(buffer.get() + bytesWritten);
}
不幸的是,这对我来说是崩溃的,没有任何线索。 有什么建议是这个概念出了什么问题吗?
最佳答案
您不能以这种方式使用 boost::shared_array
。这一行让一切都出错了:
placeHolder = boost::shared_array<uint8_t>(buffer.get() + bytesWritten)
您创建了新的 shared_array,它试图在下一个循环之后删除 [] 偏移指针,从而产生未定义的行为。你不应该在这里使用共享指针,但如果必须(比如在回调中),有一种方法可以使用 std::shared_ptr
使用别名构造函数来做到这一点:
placeHolder = std::shared_ptr<uint8_t>(
placeHolder,
placeHolder.get() + bytesWritten);
它将保持共享状态,只改变指针,数据缓冲区只会被删除一次。
工作示例 http://melpon.org/wandbox/permlink/9WP08ReJAijjCMHR
如果您绝对必须使用 boost::shared_array
,您可以使用什么都不做的删除器,但这是错误的,如果您使用该解决方案,您应该会感到不对。不,谢谢:http://melpon.org/wandbox/permlink/BR44arnH60znibAR
关于c++ - 使用 boost::shared_array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32270180/