簡體   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