Song SW
Song SW

Reputation: 1

C++11 std::unique_ptr deleter

I used the codes as follow, but g++ give me errors.

#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++ error messages.

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++ version

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) 

It seems like bad delete function.

Upvotes: 0

Views: 157

Answers (2)

Kaveh Vahedipour
Kaveh Vahedipour

Reputation: 3477

Your code is kind of fine. It is too modern for g++ 4.9. Here's how you do it with 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(){

}

Upvotes: 2

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29072

This may be a compiler bug. You are using an older version of gcc. gcc.5.4 produces the same compilation error but gcc 6.1 works fine. If you replace Func with void (*)(void *) directly, it seems to compile. It also seems to work if you define an alias for std::unique_ptr<A, Func>.

You should upgrade your compiler. If that's not possible for you, as a work around, you can try the following :

#include <memory>

class A {
};

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

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

Upvotes: 3

Related Questions