【问题标题】:C++11 std::unique_ptr deleterC++11 std::unique_ptr 删除器
【发布时间】:2017-08-31 14:16:32
【问题描述】:

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

好像删除功能不好。

【问题讨论】:

  • 是的,nullptr 不是有效的删除函数。你期待什么?
  • @nwp nullptr 不能用作删除器,但就类型系统而言,它是 Func 参数的合法值。

标签: c++ linux c++11


【解决方案1】:

这可能是编译器错误。您使用的是旧版本的 gcc。 gcc.5.4 产生相同的编译错误,但 gcc 6.1 works fine。如果直接将Func替换为void (*)(void *),似乎可以编译。如果您为 std::unique_ptr&lt;A, Func&gt; 定义别名,它似乎也可以工作。

你应该升级你的编译器。如果这对您来说不可能,作为一种解决方法,您可以尝试以下方法:

#include <memory>

class A {
};

using Func = void (*)(void *);
using MyPtr = std::unique_ptr<A, Func>;

class B {
    MyPtr b = MyPtr(nullptr, nullptr);
};

【讨论】:

  • 我更新了 gcc 版本,这个问题就消失了。但是 ASAN unrecognized option '--push-state' 还有另一个问题。所以我更新了上面的代码。效果很好,非常感谢!
【解决方案2】:

您的代码还不错。对于 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(){

}

【讨论】:

    猜你喜欢
    • 2013-03-30
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2016-11-23
    • 2021-11-10
    • 2014-06-30
    • 1970-01-01
    • 2018-04-08
    相关资源
    最近更新 更多