小编Ian*_*Ian的帖子

shared_ptr:可怕的速度

当比较两个指针变体 - 经典与shared_ptr时 - 我对程序运行速度的显着提高感到惊讶.为了测试2D Delaunay增量插入算法已被使用.

编译器设置:

VS 2010(发布)/ O2/MD/GL,W7 Prof,CPU 3.GHZ DualCore

结果:

shared_ptr(C++ 0x00):

N[points]         t[sec]  
100 000                6  
200 000               11  
300 000               16  
900 000               36  
Run Code Online (Sandbox Code Playgroud)

指针:

N[points]         t[sec]  
100 000              0,5  
200 000               1  
300 000               2  
900 000               4   
Run Code Online (Sandbox Code Playgroud)

shared_ptr版本的运行时间大约是其10倍.这是由编译器设置引起的还是C++ 0x00 shared_ptr实现那么慢?

VS2010 Profiler:对于原始指针,大约60%的时间花费在启发式搜索包含插入点的三角形上(这是一个众所周知的事实).但是对于shared_ptr版本,大约58%的时间花在使用shared_ptr.reset()上,只有10%用于启发式搜索.

使用原始指针测试代码:

void DT2D::DT ( Node2DList *nl, HalfEdgesList *half_edges_dt, bool print )
{
    // Create 2D Delaunay triangulation using incremental insertion method
    unsigned int nodes_count_before = nl->size();

    // Remove duplicit points …
Run Code Online (Sandbox Code Playgroud)

c++ compiler-construction performance shared-ptr

49
推荐指数
5
解决办法
3万
查看次数

简单的引用计数:智能指针

我想使用智能指针实现一个简单的引用计数.变量pointer表示存储对象的指针,reference_count表示对象的副本总数.

  • 如果我们使用NULL初始化一个对象:reference_count = -1 else reference_count = 1
  • copy ctor和operator = increment reference_count
  • 析构函数递减reference_count并且如果没有对指向对象的其他引用则执行其删除.

这是我的代码:

#ifndef smart_pointer_H
#define smart_pointer_H

template < typename T > class smart_pointer
{
    private:
        T*    pointer;      
        int reference_count;    

    public:

        smart_pointer() : pointer(0), reference_count(-1) {}

        smart_pointer(T* p) : pointer(p)
        {
            if (p != NULL)
            {
                this->reference_count = 1;
            }

            else
            {
                this->reference_count = -1;
            }
        }

        smart_pointer(const smart_pointer <T> & p) : pointer(p.pointer),     reference_count(p.reference_count + 1) {}
        bool operator == (const smart_pointer <T>& …
Run Code Online (Sandbox Code Playgroud)

c++ templates smart-pointers reference-counting

6
推荐指数
1
解决办法
1万
查看次数