c++ new C array allocation, RAII or simple shared_ptr / boost::shared_array

人走茶凉 提交于 2019-12-06 11:19:11

Prefer std::unique_ptr to shared_ptr. It's far faster.

std::unique_ptr<float[]> buf; //construct

try {
    buf.reset(new float[daswidth*chans_info.chans*sizeof(float)]); //give memory
}
catch (std::bad_alloc& ba) // sometimes it throws ! so i do need to stop my execution.
{
    if (DEBUG) tekstasFormat(L"WARNING: bad alloc caught: %s", ba.what());
    return; // skip this iteration then.
}

However, as Ben said, there's pretty much no reason to use a float[] like this. Instead, use std::vector. Yes, even for most* C interop.

std::vector<float> buf;

try {
    buf.resize(daswidth*chans_info.chans*sizeof(float)); //give memory
}
catch (std::bad_alloc& ba) // sometimes it throws ! so i do need to stop my execution.
{
    if (DEBUG) tekstasFormat(L"WARNING: bad alloc caught: %s", ba.what());
    return; // skip this iteration then.
}

function_expecting_float_pointer(buf.data()); //use .data() to get the `float*`

*don't use std::vector if the C code will ever "reallocate" the pointer for you. Instead, use std::unique_ptr, and (1) release the memory, (2) pass to C, (3) reset with pointer returned from C.

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