c++ - Factories: how to pass temporary smart pointers to functions. C++
问题描述
I have a class Foo
class Foo;
a factory returning a pointer to it:
std::unique_ptr<Foo> createFoo();
and, since I have been told by Herb that a plain function with no special claim on the lifetime of Foo should take plain naked pointers:
void plainf(Foo* f);
How is my client supposed to correctly do this?
plainF(createFoo());
He would not be happy if he had to write:
auto someName = createFoo();
plainF(someName.get());
解决方案
You can use the get
member function which returns a raw pointer to the owned object.
plainF(createFoo().get());
The temporary created by createFoo()
will not go out of scope until plainF
has finished. So long as plainF
doesn't pass the pointer up out of scope this is completely safe.
推荐阅读
- assembly - DASM 指令/伪指令
- java - 我在android studio中打错了吗?
- android - 有效地循环遍历 Firebase 中的多个子节点
- android - Android - android-apt 插件与 Android Gradle 插件不兼容。
- javascript - javascript 仅显示带有 promise 对象的 for 循环的最后一次迭代的输出
- python - 当检测到按键被按下时如何让Python执行命令
- c# - Additional text encountered after JSON reading
- javascript - 如何防止我的空字符串成为长度的一部分
- angular - Reset an input field to pristine without form wrapper
- java - Sub Directories under getCacheDir()