我有一个带有unique_ptr成员的类.
class Foo {
private:
std::unique_ptr<Bar> bar;
...
};
Run Code Online (Sandbox Code Playgroud)
Bar是第三方类,具有create()函数和destroy()函数.
如果我想std::unique_ptr在独立功能中使用它,我可以这样做:
void foo() {
std::unique_ptr<Bar, void(*)(Bar*)> bar(create(), [](Bar* b){ destroy(b); });
...
}
Run Code Online (Sandbox Code Playgroud)
std::unique_ptr作为班级成员,有没有办法做到这一点?
想想一个返回必须为freed的东西的C函数,例如POSIX strdup().我想在C++ 11中使用该函数并避免任何泄漏,这是正确的方法吗?
#include <memory>
#include <iostream>
#include <string.h>
int main() {
char const* t { "Hi stackoverflow!" };
std::unique_ptr<char, void(*)(void*)>
t_copy { strdup(t), std::free };
std::cout << t_copy.get() << " <- this is the copy!" <<std::endl;
}
Run Code Online (Sandbox Code Playgroud)
假设它有意义,可以使用与非指针相似的模式吗?例如,POSIX的函数open返回int?
我的一些代码仍然使用malloc而不是new.原因是因为我害怕使用,new因为它抛出异常,而不是返回NULL,我可以很容易地检查.结束语每次调用new的try{}catch(){}也看起来并不好.而在使用时malloc我可以做到if (!new_mem) { /* handle error */ }.
所以我有一个问题.我可以同时使用智能指针malloc吗?
就像是:
SmartPointer<Type> smarty = malloc(sizeof(Type));
Run Code Online (Sandbox Code Playgroud)
像这样的东西.
这可能吗?
谢谢,Boda Cydo.