当我尝试为仅移动类编写单元测试时遇到了这个问题。 [我不知道如何编写测试来检查移动操作是否确实移动了类的数据成员。在这里,我提供了一个与我正在研究的并行的类的简化示例。实际上,该类支持更多的操作和(std::multimap
)数据成员,在这里不相关。
#include <vector>
class MyClass {
public:
inline MyClass() = default;
MyClass(const MyClass& other) = delete;
MyClass(MyClass&& other) = default;
MyClass& operator=(const MyClass& other) = delete;
MyClass& operator=(MyClass&& other) = default;
~MyClass() = default;
inline void set(const std::vector<MyStruct>& data) {data_ = data;}
inline const std::vector<MyStruct>& get() {return data_;}
private:
std::vector<MyStruct> data_;
};
[MyStruct
]仅包含原始数据类型(int
,float
和double
),并且某些std::string
类型作为(public
)数据成员。为了完整起见,我在末尾添加了MyStruct
的定义。
我不确定该如何开始,也无法通过在线搜索找到任何东西。理想情况下,googletest或googlemock解决方案将是很好的选择,但是仅是通用方法或在其他测试框架中如何完成它,可能会帮助我理解并在首选的框架中实现。
#include <string>
struct MyStruct {
int foo;
float bar;
double baz;
std::string fips;
};
这里是一种使用Marker成员变量跟踪对象状态的方法。请记住,std::move
并不意味着将对象[[will从中移出,而只是使对象eligible从中被移出。
std::vector
和std::unique_ptr
。)#include <iostream>
#include <string>
#include <vector>
#ifndef TESTING
#define TESTING 1
#endif
namespace {
struct Marker final {
char const* state;
~Marker() { state = "destructed"; }
Marker() : state{"constructed"} {}
Marker(Marker const&) noexcept : state{"copy constructed"} {}
Marker(Marker&& other) noexcept : state{"move constructed"} { other.state = "move constructed husk"; }
Marker& operator=(Marker const&) noexcept { state = "assigned"; return *this; }
Marker& operator=(Marker&& other) noexcept { state = "move assigned"; other.state = "move assigned husk"; return *this; }
void print(std::ostream&) const;
};
void Marker::print(std::ostream& out) const {
out << state;
}
std::ostream& operator<<(std::ostream& out, Marker const& marker) {
marker.print(out);
return out;
}
class BigFancyClass {
std::vector<std::string> v;
public:
BigFancyClass() {}
BigFancyClass(BigFancyClass const&) = default;
BigFancyClass(BigFancyClass&&) = default;
#if TESTING
Marker mark;
#endif
};
void test() {
BigFancyClass bfc;
std::cout << "bfc: " << bfc.mark << "\n";
BigFancyClass bfc2 = std::move(bfc);
std::cout << "bfc: " << bfc.mark << "\n";
std::cout << "bfc2: " << bfc2.mark << "\n";
}
} // anon
int main() {
test();
}