【发布时间】:2016-10-28 12:46:19
【问题描述】:
我正在尝试为接受 a) 接口的实现的接口类编写一个adapter 类,该接口应该是堆栈分配的(因此不需要从外部进行新/删除处理,适配器本身可以使用 new/delete) 和 b) 将由接口的相应实现调用的 lambda 函数。
#include <iostream>
#include <functional>
struct interface {
virtual int hello() = 0;
};
struct implementation : public interface {
virtual int hello() {
std::cout << "hello()\n";
return 42;
}
};
struct adapter {
interface* obj;
adapter(std::function<int()>&& func) {
struct lambda : public interface {
std::function<int()> func;
lambda(std::function<int()> func_): func(func_) { }
virtual int hello() {
return this->func();
}
};
this->obj = new lambda{func};
}
adapter(interface&& impl) {
// TODO: pretty sure that's incorrect
// but can I somehow create a copy of "impl" on the heap?
this->obj = &impl;
}
};
int main() {
adapter a([]() { std::cout << "hello from lambda\n"; return 99; });
a.obj->hello();
#if 0
// ERROR
adapter b(implementation());
b.obj->hello();
#endif
return 0;
}
这是我在启用adapter b 部分时遇到的错误。
prog.cpp: In function 'int main()':
prog.cpp:39:4: error: request for member 'obj' in 'b', which is of non-class type 'adapter(implementation (*)())'
b.obj->hello();
^
- 我完全不理解错误,非常感谢您的解释
- 我怎样才能真正正确地实现
adapter(interface&&)构造函数?我可能需要在堆上创建对象的副本,否则在adapater构造函数之后它不会持久化
在 ideone 上测试:http://ideone.com/Gz3ICk 使用 C++14 (gcc-5.1)
PS:是的,adapter 类缺少一个析构函数,该析构函数应该删除从 lambda 构造函数创建的 obj
【问题讨论】:
-
您需要一个“虚拟复制构造函数”来复制多态基类(这是一个虚拟克隆函数)。
-
@DieterLücking 好的,我希望可以在没有虚拟复制功能的情况下以某种方式复制右值。
interface const&而不是interface&&可能是同样的情况?使用虚拟复制功能会破坏我的目标设计。
标签: c++ c++11 interface move-semantics object-lifetime