繁体   English   中英

计算std :: vector的复制和移动数量

[英]Counting the number of copy and move of a std::vector

我有一个用C ++ 11编写的程序,我想计算std::vector<double>对象的移动和复制(构造和赋值)次数。 有没有办法做到这一点?

最好的祝福

不行 std::vector<>实现对此没有提供任何方法。 我所不知道的任何编译器。

如评论中所述,您可以创建自己的计数替换并使用它。

struct counting_vector_double
: std::vector<double>
{
  static size_t count_copy_ctor;
  static size_t count_move_ctor;

  counting_vector_double(counting_vector_double const&other)
  : std::vector<double>(other)
  { count_copy_ctor++; }

  // etc
};

// in .cc file:
size_t counting_vector_double::count_copy_ctor = 0;
size_t counting_vector_double::count_move_ctor = 0;

(在多线程情况下,请使用atomic计数器。)要实现此目的,可以使用typedefusing指令,例如

#ifdef CountingMoveCopy
using vector_double = counting_vector_double;
#else
using vector_double = std::vector<double>;
#endif

并在代码中使用vector_double

此答案认为,OP需要计算向量项被复制,移动,构造等的次数,而不是向量本身。


尽管这不是您问题的直接答案,但您可能对此答案感兴趣。

围绕double制作一个小型包装器类:

struct double_wrapper{
    double_wrapper()=delete;
    double_wrapper(const double value):value_(value){
        ++constructions_count;
    }
    double_wrapper(const double_wrapper& other){
        value_=other.value_;
        ++copies_count;
    }
    double_wrapper(double_wrapper&& other){
        value_=other.value_;
        //invalidate it in someway.. maybe set it to 0 (not important anyway)
        ++moves_count;
    }
    operator double() const {
         return value_;
    }

    double value_;
    static unsigned int copies_count;
    static unsigned int constructions_count;
    static unsigned int moves_count;
}

// in .cpp
unsigned int double_wrapper::copies_count=0;
unsigned int double_wrapper::constructions_count=0;
unsigned int double_wrapper::moves_count=0;

最后,您必须编辑vector类型(您可以使用一些#ifdef其简称为“调试模式”):

std::vector<double_wrapper> v1;

注意:未经测试。

规避该限制的一种可能方法是,使Vector类继承一个std :: vector,然后重载move和copy运算符以增加内部计数器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM