C++11 std::unique_ptr deleter
C++11 std::unique_ptr deleter
我使用的代码如下,但是G 给我错误。
#include <stdio.h>
#include <memory>
using Func = void (*)(void *p);
class A {
};
class B {
std::unique_ptr<A, Func> b = std::unique_ptr<A, Func>(nullptr, nullptr);
};
int main()
{
}
g 错误消息。
test.cc:10:50: error: expected ‘;’ at end of member declaration
std::unique_ptr<A, Func> b = std::unique_ptr<A, Func>(nullptr, nullptr);
^
test.cc:10:50: error: declaration of ‘std::unique_ptr<A, void (*)(void*)> B::Func’ [-fpermissive]
test.cc:4:31: error: changes meaning of ‘Func’ from ‘using Func = void (*)(void*)’ [-fpermissive]
using Func = void (*)(void *p);
^
test.cc:10:54: error: expected unqualified-id before ‘>’ token
std::unique_ptr<A, Func> b = std::unique_ptr<A, Func>(nullptr, nullptr);
^
test.cc:10:47: error: template argument 1 is invalid
std::unique_ptr<A, Func> b = std::unique_ptr<A, Func>(nullptr, nullptr);
^
test.cc:10:47: error: template argument 2 is invalid
g 版本
root@ubuntu-linux:~/trafficserver/iocore/net/quic# g++ test.cc -std=c++11^C
root@ubuntu-linux:~/trafficserver/iocore/net/quic# g++ -v
gcc version 4.9.4 (Ubuntu 4.9.4-2ubuntu1~14.04.1)
似乎不良删除函数。
这可能是编译器错误。您正在使用旧版本的GCC。GCC.5.4产生相同的汇编错误,但GCC 6.1工作正常。如果将Func
直接替换为CC_1,则似乎会编译。如果您定义了std::unique_ptr<A, Func>
的别名。
您应该升级编译器。如果您无法做到这一点,则可以尝试以下操作:
#include <memory>
class A {
};
using Func = void (*)(void *);
using MyPtr = std::unique_ptr<A, Func>;
class B {
MyPtr b = MyPtr(nullptr, nullptr);
};
您的代码很好。对于G 4.9来说太现代了。这是您使用G 4.9
进行操作的方式class A {
};
void Func(void*) {
}
class B {
std::unique_ptr<A, decltype(&Func)> b =
std::unique_ptr<A, decltype(&Func)>(nullptr, nullptr);
};
int main(){
}
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- 带有自定义deleter的std::unique_ptr对象的大小(一个由ref捕获的lambda)
- C++中的指针否定 (!ptr == NULL)
- primr 5版.自定义deleter函数的unique_ptr构造函数
- 从const ptr*转换为ptr*时出现问题
- 这是MSVC 2013中具有共享PTR的单例的正确实现吗?
- 对唯一 ptr 无效读取的引用向量
- C++ 类型转换基础 PTR 到派生 PTR 保存在引用类中