在给定的示例中避免内存重新分配

时间:2016-02-14 21:25:58

标签: c++ optimization allocation ros

该函数被非常频繁地调用,所以我尝试降低内存重新分配等。令我烦恼的是vectorint,虽然我不能将它们移到函数之外,否则我得{ {1}}。到目前为止,我有:

std::bad_alloc

1 个答案:

答案 0 :(得分:1)

您是否对应用程序进行了分析?你的代码真的是瓶颈吗?如果你有......那么

好吧,如果你使用的是C ++ 11编译器,你可以这样做,如果你没有C ++ 11编译器,删除thread_local但是你必须要处理reentrancy如果有可能在多线程代码中调用该例程

void callbString(const std_msgs::String::ConstPtr& msg)
{
    static thread_local vector<string> cbstrVec;
    static thread_local std::string str;

    int cbtype;  //int is super cheap

    cbstrVec.clear();

    //get string and split into vector
    str = (msg->data.c_str());
    if(str.empty()) return;
    str.erase(0,1);
    boost::split(cbstrVec, str, boost::is_any_of(" "));
    stringstream(cbstrVec[2])>>cbtype;
    //c.setvec(cbstrVec,cbtype); //takes (vector<string>,int) 
    c.setvec(std::move(cbstrVec),cbtype); //takes (vector<string>,int) 
}

cbstrVecstr将重用其内存,因为cbstrVec.clear()并未真正解除分配向量分配的所有内存,并且重新分配str将重用内部存储一个好的STL实现