计算 std::vector 的复制和移动次数
Counting the number of copy and move of a std::vector
>我有一个用 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
计数器。要实现这一点,您可以使用 typedef
或 using
指令,例如
#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,然后重载移动和复制运算符以增加内部计数器。
相关文章:
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 如何在窗口之间移动 std::unique_ptr 而不会冒内存泄漏的风险?
- 为什么移动 std::可选不重置状态
- C++:我可以重用/移动 std::list 元素从中间到结尾吗?
- 我应该移动 std::exchange ed 成员吗?
- 移动 std::bitset<N> 是否超过 N 个位置未定义的行为?
- 标准是否保证在移动std::p ackaged_task后安全使用std::future?
- 用于移动 std::shared_ptr 的函数声明
- 如何移动 std::ostringstream 的底层字符串对象?
- 移动std::shared_ptr会使程序崩溃
- c++11移动std::deque或std::list的插入
- 如何移动std::ostream
- 移动std::bind和std::thread中的语义/行为
- 为什么我不能移动 std::ofstream?
- 从char*中移动std::string的构造函数
- 移动 std::vector 成员的语义
- 移动std::unique_locks的std::矢量
- 复制/移动std::映射中键/值类型的要求
- 移动std::互斥锁的构造函数
- 在容器之间移动std::unique_ptr