我有一个返回智能指针的工厂.无论我使用什么智能指针,我都无法让 Google Mock 模拟工厂方法.
I have a factory that returns a smart pointer. Regardless of what smart pointer I use, I can't get Google Mock to mock the factory method.
模拟对象是一个纯抽象接口的实现,其中所有方法都是虚拟的.我有一个原型:
The mock object is the implementation of a pure abstract interface where all methods are virtual. I have a prototype:
MOCK_METHOD0(Create, std::unique_ptr<IMyObjectThing>());
我得到:
"...gmock/gmock-spec-builders.h(1314): error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'"
定义了智能指针指向的类型.
The type pointed to in the smart pointer is defined.
我知道它试图访问声明为私有的构造函数之一,但我不明白为什么.当这是一个 std::auto_ptr 时,错误说没有复制构造函数,这让我很困惑.
And I get it's trying to access one of the constructors declared private, but I don't understand why. When this was an std::auto_ptr, the error said there was no copy constructor, which confuses me.
无论如何,有没有办法模拟一个返回智能指针的方法?或者有没有更好的建厂方式?我唯一的决心是返回一个原始指针(blech ...)吗?
Anyway, is there a way to Mock a method that returns a smart pointer? Or is there a better way to build a factory? Is my only resolve to return a raw pointer (blech...)?
我的环境是 Visual Studio 2010 Ultimate 和 Windows 7.我没有使用 CLI.
My environment is Visual Studio 2010 Ultimate and Windows 7. I'm not using CLI.
在大多数情况下,Google Mock 要求模拟方法的参数和返回值是可复制的.根据 boost 的文档,unique_ptr 是不可复制.您可以选择返回使用共享所有权的智能指针类之一 (shared_ptr、linked_ptr 等),因此是可复制的.或者您可以使用原始指针.由于所讨论的方法显然是构造对象的方法,因此我认为返回原始指针没有固有的问题.只要您将结果分配给每个调用站点的某个共享指针,您就会没事.
Google Mock requires parameters and return values of mocked methods to be copyable, in most cases. Per boost's documentation, unique_ptr is not copyable. You have an option of returning one of the smart pointer classes that use shared ownership (shared_ptr, linked_ptr, etc.) and are thus copyable. Or you can use a raw pointer. Since the method in question is apparently the method constructing an object, I see no inherent problem with returning a raw pointer. As long as you assign the result to some shared pointer at every call site, you are going to be fine.
这篇关于Google 可以模拟具有智能指针返回类型的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!