I am creating an object file for my larger program. In this program I use a unique_ptr
type with a custom deleter defined.
So I'm compiling my file like so:
g -std=c 20 tmp.cpp -c -Wall
The code looks as follows:
#include <memory>
using specialptr = std::unique_ptr<int, decltype([](int *f) {
delete f;
})>;
specialptr fun(){
return specialptr{new int};
}
This generates this warning:
tmp.cpp:12:12: warning: ‘specialptr fun()’ defined but not used [-Wunused-function]
12 | specialptr fun(){ return specialptr{new int};}
|
When I link this object file with a main.cpp
that calls the function I get the following error:
In file included from main.cpp:1:
tmp.h:19:12: warning: ‘specialptr fun()’ used but never defined
19 | specialptr fun();
| ^~~
/usr/bin/ld: /tmp/ccnuTTGC.o: in function `main':
main.cpp:(.text 0x4c): undefined reference to `fun()'
collect2: error: ld returned 1 exit status
What is going on here? My code works when I change the return value from a unique_ptr
to a normal pointer. But intuitively, I defined the type and function and made a declaration in a header file.
g is version: g (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
CodePudding user response:
You can use object type as deleter. In this case you don't need to set it every time you create std::unique_ptr
.
#include <memory>
#include <iostream>
struct MyDeleter {
void operator()(int *f) {
std::cout << "Deleter called";
delete f;
}
};
using specialptr = std::unique_ptr<int, MyDeleter>;
specialptr fun(){
return specialptr{new int};
}
int main()
{
auto x = fun();
}
CodePudding user response:
The decltype
of a lambda is different for each translation unit.
You can instead do something like:
struct specialptr_deleter {
void operator()(int *f) const {
delete f;
}
};
using specialptr = std::unique_ptr<int, specialptr_deleter>;
specialptr fun(){
return specialptr{new int};
}