【发布时间】:2017-06-01 21:15:53
【问题描述】:
我正在测试 unique_ptr 的自定义删除器。
奇怪的是,只有作为函数对象的删除器才能正常工作。
如果我用函数或 lambda 替换它们,程序将无法编译。
我做错了什么?
这是我完整的测试程序
#include <iostream>
#include <memory>
using namespace std;
class Vehicle {
public:
Vehicle(){ cout<<"Vehicle constructor..."<<endl;}
virtual ~Vehicle(){cout<<"~Vehicle destructor..."<<endl;}
virtual void go()=0;
};
class Car:public Vehicle {
public:
void go() override {
cout<<"Going by car..."<<endl;
}
};
class Bicycle:public Vehicle {
public:
void go() override {
cout<<"Going by bicycle..."<<endl;
}
};
// Custom deleters
auto CustomLambdaDeleter = [](Vehicle* v){
cout<<"Custom lambda deleter called..."<<endl;
delete v;
};
void CustomFunctionDeleter(Vehicle* v){
cout<<"Custom function deleter called..."<<endl;
delete v;
}
struct CustomFunctorDeleter
{
void operator()(Vehicle* v ) const {
cout<<"Custom functor deleter called..."<<endl;
delete v;
}
};
// Doesn't compile
//using VehiclePtr = unique_ptr<Vehicle, decltype(CustomLambdaDeleter)>;
// Doesn't compile
//using VehiclePtr = unique_ptr<Vehicle, decltype(&CustomFunctionDeleter)>;
// Works ok
using VehiclePtr = unique_ptr<Vehicle, CustomFunctorDeleter>;
class VehicleFactory {
public:
static VehiclePtr createVehicle(string type){
VehiclePtr vptr;
if("bicycle"==type) {
vptr.reset(new Bicycle());
// This also works
// vptr= (VehiclePtr) new Bicycle();
return vptr;
}
else if("car"==type) {
vptr.reset( new Car());
return vptr;
}
return nullptr;
}
};
void vehicleFactoryTest(){
cout<<"* Starting vehicleFactoryTest()..."<<endl;
auto firstVehicle = VehicleFactory::createVehicle("bicycle");
firstVehicle->go();
auto newCar = VehicleFactory::createVehicle("car");
newCar->go();
}
int main(int, char **)
{
vehicleFactoryTest();
return 0;
}
【问题讨论】:
-
为了帮助人们回答您的问题,您需要更具体地说明错误。请edit 您的帖子包含您从minimal reproducible example 获得的确切错误(最好使用复制+粘贴以避免转录错误)。
-
我收到以下错误:使用已删除的函数 '
:: ()'
标签: c++ c++11 lambda unique-ptr