简体   繁体   English

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

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

I have a program written in C++11 and I would like to count the number of move and copy (construction and assignment) of std::vector<double> objects. 我有一个用C ++ 11编写的程序,我想计算std::vector<double>对象的移动和复制(构造和赋值)次数。 Is there a way to do that? 有没有办法做到这一点?

Best regards 最好的祝福

No . 不行 The implementation of std::vector<> provides no way for that. std::vector<>实现对此没有提供任何方法。 Neither does any compiler I know of. 我所不知道的任何编译器。

As mentioned in the comments, you could create your own counting replacement and use that instead. 如评论中所述,您可以创建自己的计数替换并使用它。 Ie

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;

(in a multi-threaded situation use atomic counters.) To implement this, you may use a typedef or using directive, like (在多线程情况下,请使用atomic计数器。)要实现此目的,可以使用typedefusing指令,例如

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

and use vector_double in your code. 并在代码中使用vector_double

This answer consider that the OP needs to count the how many times the items of the vector are copied, moved, constructed.. etc) not the vector itself. 此答案认为,OP需要计算向量项被复制,移动,构造等的次数,而不是向量本身。


Although it is not a direct answer to your question, you may be interested in this answer. 尽管这不是您问题的直接答案,但您可能对此答案感兴趣。

Make a small wrapper class around double: 围绕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;

Finally, you have to edit the vector type (you may short it to Debug Mode with some #ifdef ): 最后,您必须编辑vector类型(您可以使用一些#ifdef其简称为“调试模式”):

std::vector<double_wrapper> v1;

Note: not tested. 注意:未经测试。

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

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

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