小编Fra*_*ndi的帖子

Push_back比插入更快?

我正在使用std::deque.我确信替代与循环push_back有一个insert会产生性能的提高.例如,这里也建议使用它.

但现在我不再那么肯定了.

我在测试代码上运行了一些基准测试.

Main.cpp的:

#include"queueInsert.h"

#include<Windows.h>

std::deque<int> queue;

constexpr size_t len = 64;

int arr[len];

int main()
{
    DWORD startTime = GetTickCount();
    for (int i = 0; i < 100000; ++i)
    {
        insert(queue, arr, len);
    }
    DWORD endTime = GetTickCount();

    return endTime - startTime;
}
Run Code Online (Sandbox Code Playgroud)

queueInsert.h:

#include<deque>

void insert(std::deque<int>&, int* arr, int n);
Run Code Online (Sandbox Code Playgroud)

queueInsert.cpp -push版本

#include "queueInsert.h"

void insert(std::deque<int>& queue, int* arr, int n)
{
    for (int i = 0; i < …
Run Code Online (Sandbox Code Playgroud)

c++ performance stl

7
推荐指数
1
解决办法
1416
查看次数

聪明智能指针:避免shared_ptr过度使用

我遇到过类似的代码

bool open_resource(..., shared_ptr<resource> & res)
{
   ...
   shared_ptr<resource> newResource(new resource(...));
   res = move(newResource);
   return true;
}
Run Code Online (Sandbox Code Playgroud)

随后调用

shared_ptr<resource> res;
open_resource(..., res);
Run Code Online (Sandbox Code Playgroud)

然后,就我所见,res不会以需要共享指针的方式使用.

我当然想到了改变

   shared_ptr<resource> newResource(new resource(...));
   res = move(newResource);
Run Code Online (Sandbox Code Playgroud)

res = make_shared<resource>(...)
Run Code Online (Sandbox Code Playgroud)

......但后来我遇到了障碍.现在我再也不能建议将shared_ptr引用更改为更基本的引用; 至少不是如果我想确保,如果调用者实际上需要以后的shared_ptr,则控制块有效地驻留在与对象相同的分配上.要使其工作,它必须从头开始是shared_ptr.

另一方面,shared_ptr是一种"重型"; 它有两个计数器和别名以及在大多数呼叫站点中真正看起来不需要的各种功能.然而,如果它是签名中的shared_ptr,那么他们必须使用它.

我看到的最佳解决方案是将函数体移动到辅助函数,然后重载.

bool get_resource_parameters(Param1& param1,..., ParamN& paramN)
{
   ...
}

bool open_resource(..., shared_ptr<resource> & res)
{
   Param1 param1;
   ...
   ParamN paramN;
   if(!get_resource_parameters(param1,...,paramN))
       return false;

   res = make_shared<resource>(param1,...,paramN);
   return true;
}

bool open_resource(..., unique_ptr<resource> & res)
{
   Param1 param1;
   ...
   ParamN paramN;
   if(!get_resource_parameters(param1,...,paramN))
       return …
Run Code Online (Sandbox Code Playgroud)

c++ smart-pointers c++11

3
推荐指数
1
解决办法
1618
查看次数

标签 统计

c++ ×2

c++11 ×1

performance ×1

smart-pointers ×1

stl ×1