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

Counting the number of copy and move of a std::vector

本文关键字:移动 std vector 计算 复制      更新时间:2023-10-16

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

此致敬意

No.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,然后重载移动和复制运算符以增加内部计数器。