提交 58efbf41 编写于 作者: Y Yi Wang

Follow comments from Xu Wei

上级 5a22d736
...@@ -12,6 +12,8 @@ ...@@ -12,6 +12,8 @@
*/ */
#pragma once #pragma once
#include <memory>
#include <typeindex>
#include <typeinfo> #include <typeinfo>
namespace paddle { namespace paddle {
...@@ -26,24 +28,14 @@ class Variable { ...@@ -26,24 +28,14 @@ class Variable {
template <typename T> template <typename T>
T* GetMutable() { T* GetMutable() {
if (holder_ != nullptr && typeid(T) == holder_->Type()) { if (holder_ == nullptr ||
return static_cast<T*>(holder_->Ptr()); std::type_index(typeid(T)) != std::type_index(holder_->Type())) {
} else { holder_.reset(new PlaceholderImpl<T>(new T()));
return Reset<T>(new T(), DefaultDeleter<T>());
}
} }
return static_cast<T*>(holder_->Ptr());
~Variable() {
if (holder_ != nullptr) delete holder_;
} }
private: private:
// DefaultDeleter is functor which uses C++'s delete(T*).
template <typename T>
struct DefaultDeleter {
void operator()(T* ptr) { delete ptr; }
};
struct Placeholder { struct Placeholder {
virtual ~Placeholder() {} virtual ~Placeholder() {}
virtual const std::type_info& Type() const = 0; virtual const std::type_info& Type() const = 0;
...@@ -54,34 +46,17 @@ class Variable { ...@@ -54,34 +46,17 @@ class Variable {
// parameter of Variable. // parameter of Variable.
template <typename T> template <typename T>
struct PlaceholderImpl : public Placeholder { struct PlaceholderImpl : public Placeholder {
typedef std::function<void(T*)> Deleter;
PlaceholderImpl(T* ptr) : ptr_(ptr), type_(typeid(T)) {} PlaceholderImpl(T* ptr) : ptr_(ptr), type_(typeid(T)) {}
PlaceholderImpl(T* ptr, Deleter d)
: ptr_(ptr), type_(typeid(T)), deleter_(d) {}
virtual ~PlaceholderImpl() {
deleter_(ptr_);
ptr_ = nullptr;
}
virtual const std::type_info& Type() const { return type_; } virtual const std::type_info& Type() const { return type_; }
virtual void* Ptr() const { return ptr_; } virtual void* Ptr() const { return static_cast<void*>(ptr_.get()); }
T* ptr_ = nullptr; std::unique_ptr<T> ptr_;
const std::type_info& type_; const std::type_info& type_;
std::function<void(T*)> deleter_ = DefaultDeleter<T>();
}; };
template <typename T> std::unique_ptr<Placeholder>
T* Reset(T* allocated, typename PlaceholderImpl<T>::Deleter deleter) { holder_; // pointers to a PlaceholderImpl object indeed.
if (holder_ != nullptr) {
delete holder_;
}
holder_ = new PlaceholderImpl<T>(allocated, deleter);
return allocated;
}
Placeholder* holder_; // pointers to a PlaceholderImpl object indeed.
}; };
} // namespace framework } // namespace framework
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册