简体   繁体   中英

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. Is there a way to do that?

Best regards

No . The implementation of std::vector<> provides no way for that. 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

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

and use vector_double in your code.

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.


Although it is not a direct answer to your question, you may be interested in this answer.

Make a small wrapper class around 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 ):

std::vector<double_wrapper> v1;

Note: not tested.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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