【发布时间】:2017-04-18 23:21:27
【问题描述】:
背景
我想要一个类MyClass 来存储不同类型的队列。为此,我创建了一个接口ValueInterface 和一个派生类Value<T>。我现在可以使用queue<ValueInterface> 成员变量将这个派生类的实例存储在MyClass 中。
注意:出于我自己的目的,我故意尝试将MyClass 保持为非模板化,并且我想依赖模板化函数。
目标
我有下面的代码可以编译,但在下面的测试代码中运行会导致核心转储。我认为我在使用std::unique_ptr 时要小心,并确保在可能的情况下使用std::move。 GetValueAndAdvance<T> 函数会导致错误。当我尝试从模板化队列中检索时出现问题。我知道这很混乱,我假设 static_cast 可以工作,但是我怎样才能从存储 ValueInterface 的 std::queue 中检索 Value<T> ? p>
我不知道问题出在StoreValue 或GetValueAndAdvance 上,还是整个设计存在缺陷,无法在类型敏感的语言中实现。
在测试中的使用:
这是我想要完成的功能。这是假设每个MyClass 一次只能用于一种类型。所以让我们假设没有人会在同一个MyClass 对象上调用StoreValue<int>(4) 和StoreValue<string>("hello")。但出于我自己的原因,我想保留MyClass 非模板化。
MyClass my_class;
my_class.StoreValue<int>(5);
int val;
my_class.GetValueAndAdvance<int>(&val);
std::cout << "value: " << val; // Should print "value: 5"
代码:
class ValueInterface {};
template <class T>
class Value : public ValueInterface {
public:
Value(T val) : value_(val){};
T get() { return value_; }
private:
const T& value_;
};
class MyClass {
public:
template <class T>
void GetValueAndAdvance(T* out_val) {
if (!queued_values_.empty()) {
auto unique_value = std::move(queued_values_.front());
queued_values_.pop();
auto unique_value_typed = static_cast<Value<T>*>(unique_value.get());
*out_val = unique_value_typed->get();
// Prints 0 even though it should return 5 based on the test code (below)
std::cout << "value: " << unique_value_typed->get();
}
return;
}
template <class T>
MyClass* StoreValue(const T& value) {
auto wrapped_value = std::make_unique<Value<T>>(value);
queued_values_.push(std::move(wrapped_value));
return this;
}
private:
std::queue<std::unique_ptr<ValueInterface>> queued_values_;
};
错误消息的 sn-p
F0418 18:08:57.928949 244111 debugallocation.cc:763] RAW: delete size mismatch: passed size 1 != true size 4
@ 0x7fda024f8a1f (anonymous namespace)::RawLogVA()
@ 0x7fda024f8525 base_raw_logging::RawLog()
@ 0x42b162 tc_delete_sized
@ 0x40c595 std::default_delete<>::operator()()
@ 0x40c503 std::unique_ptr<>::~unique_ptr()
@ 0x40b552 mynamespace::MyClass::GetValueAndAdvance<>()
【问题讨论】:
标签: c++ templates c++14 unique-ptr coredump