相关疑难解决方法(0)

如何将自定义删除器与std :: unique_ptr成员一起使用?

我有一个带有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作为班级成员,有没有办法做到这一点?

c++ unique-ptr move-semantics c++11

122
推荐指数
7
解决办法
9万
查看次数

std :: unique_ptr用于需要免费的C函数

想想一个返回必须为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

c++ c++11

50
推荐指数
5
解决办法
9886
查看次数

是否可以将C++智能指针与C的malloc一起使用?

我的一些代码仍然使用malloc而不是new.原因是因为我害怕使用,new因为它抛出异常,而不是返回NULL,我可以很容易地检查.结束语每次调用newtry{}catch(){}也看起来并不好.而在使用时malloc我可以做到if (!new_mem) { /* handle error */ }.

所以我有一个问题.我可以同时使用智能指针malloc吗?

就像是:

SmartPointer<Type> smarty = malloc(sizeof(Type));
Run Code Online (Sandbox Code Playgroud)

像这样的东西.

这可能吗?

谢谢,Boda Cydo.

c++ malloc smart-pointers new-operator

23
推荐指数
2
解决办法
1万
查看次数