Google 可以模拟具有智能指针返回类型的方法吗?

Can Google Mock a method with a smart pointer return type?(Google 可以模拟具有智能指针返回类型的方法吗?)
本文介绍了Google 可以模拟具有智能指针返回类型的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个返回智能指针的工厂.无论我使用什么智能指针,我都无法让 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 可以模拟具有智能指针返回类型的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)