C++11 std::unique_ptr deleter

C++11 std::unique_ptr deleter

本文关键字:ptr deleter unique std C++11      更新时间:2023-10-16

我使用的代码如下,但是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(){
}