unique_ptr w/ custom deleter in header

Nick nospam@codesniffer.com
Sat Jan 19 09:48:00 GMT 2013


When I use a std::unique_ptr w/ a custom deleter via an inline lambda in
a non-template function implemented inline in a header file, I get a
linker error.

I'm using gcc 4.7.2 on Linux.

Here (and attached) is a sample which shows 3 variations of the usage.  

Note that the specifics of this example are only for demonstration
purposes--I'm not actually trying to use a custom deleter to perform
what the default implementation does.

//----------------------------------------------------------

nick@nimble ~/UniquePtrTest $ cat ./main.cpp 
#include <memory>

#include "UniquePtrTest.h"

void Foo1()
{
	std::unique_ptr<char, void(*)(char*)> p(
		new char[5],
		[](char * p)
		{
			delete(p);
		}
	);
}

int main()
{
	Foo1();
	Foo2<int>();
	Foo3();
	Foo4();
}
//----------------------------------------------------------

nick@nimble ~/UniquePtrTest $ cat ./UniquePtrTest.h 
#include <memory>		// for std::unique_ptr


template<typename T>
void Foo2()
{
	std::unique_ptr<char, void(*)(char*)> p(
		new char[5],
		[](char * p)
		{
			delete(p);
		}
	);
}

inline
void Foo3()
{
	auto myDeleter = [](char * p)
	{
		delete p;
	};
	std::unique_ptr<char, decltype(myDeleter)> p(
		new char[5],
		myDeleter
	);
}

inline
void Foo4()
{
	std::unique_ptr<char, void(*)(char*)> p(
		new char[5],
		[](char * p)
		{
			delete(p);
		}
	);
}
//----------------------------------------------------------


Foo1, Foo2, and Foo3 all compile and link fine.  Only Foo4 yields a
linker error:

nick@nimble ~/UniquePtrTest $ g++ -std=c++11  ./main.cpp 
/tmp/cc98v9Mr.o: In function `Foo4()::{lambda(char*)#1}::operator void (*)(char*)() const':
main.cpp:(.text._ZZ4Foo4vENKUlPcE_cvPFvS_EEv[_ZZ4Foo4vENKUlPcE_cvPFvS_EEv]+0x4): undefined reference to `Foo4()::{lambda(char*)#1}::_FUN(char*)'
collect2: error: ld returned 1 exit status


Is this expected?


Best regards,
Nick

-------------- next part --------------
A non-text attachment was scrubbed...
Name: main.cpp
Type: text/x-c++src
Size: 218 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc-help/attachments/20130119/514323b3/attachment.bin>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: UniquePtrTest.h
Type: text/x-chdr
Size: 453 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc-help/attachments/20130119/514323b3/attachment-0001.bin>


More information about the Gcc-help mailing list