From a43fac35676ba391da1aabaadd3edb19fab4e087 Mon Sep 17 00:00:00 2001 From: Yu Yang Date: Sun, 11 Feb 2018 14:38:14 +0800 Subject: [PATCH] Fix empty Vector foreach Fix #8368 --- paddle/fluid/framework/mixed_vector.h | 33 +++++++++++++-------- paddle/fluid/framework/mixed_vector_test.cu | 6 ++++ 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/paddle/fluid/framework/mixed_vector.h b/paddle/fluid/framework/mixed_vector.h index 4dc3de54de..a35ec5d1de 100644 --- a/paddle/fluid/framework/mixed_vector.h +++ b/paddle/fluid/framework/mixed_vector.h @@ -106,9 +106,9 @@ class Vector { // std::vector iterator methods. Based on CPU data access method size_t size() const { return size_; } - T* begin() { return &this->operator[](0); } + T* begin() { return size() == 0 ? &EmptyDummy() : &this->operator[](0); } - T* end() { return &this->operator[](size()); } + T* end() { return size() == 0 ? &EmptyDummy() : &this->operator[](size()); } T& front() { return *begin(); } @@ -118,12 +118,12 @@ class Vector { return *it; } - const T* begin() const { return &this->operator[](0); } - const T* end() const { return &this->operator[](size()); } - - const T* cbegin() const { return begin(); } - - const T* cend() const { return end(); } + const T* begin() const { + return size() == 0 ? &EmptyDummy() : &this->operator[](0); + } + const T* end() const { + return size() == 0 ? &EmptyDummy() : &this->operator[](size()); + } const T& back() const { auto it = end(); @@ -240,16 +240,18 @@ class Vector { // implicit cast operator. Vector can be cast to std::vector implicitly. operator std::vector() const { std::vector result; - result.resize(size()); - std::copy(begin(), end(), result.begin()); + if (size() == 0) { + result.resize(size()); + std::copy(begin(), end(), result.begin()); + } return result; } bool operator==(const Vector& other) const { if (size() != other.size()) return false; - auto it1 = cbegin(); - auto it2 = other.cbegin(); - for (; it1 < cend(); ++it1, ++it2) { + auto it1 = begin(); + auto it2 = other.begin(); + for (; it1 < end(); ++it1, ++it2) { if (*it1 != *it2) { return false; } @@ -358,6 +360,11 @@ class Vector { } } + static T& EmptyDummy() { + static T dummy = T(); + return dummy; + } + mutable int flag_; mutable Tensor cpu_vec_; mutable Tensor cuda_vec_; diff --git a/paddle/fluid/framework/mixed_vector_test.cu b/paddle/fluid/framework/mixed_vector_test.cu index 0d5a914eac..8ea574b31c 100644 --- a/paddle/fluid/framework/mixed_vector_test.cu +++ b/paddle/fluid/framework/mixed_vector_test.cu @@ -98,3 +98,9 @@ TEST(mixed_vector, InitWithCount) { ASSERT_EQ(vec[i], 10); } } + +TEST(mixed_vector, ForEach) { + vec tmp; + for (auto& v : tmp) { + } +} -- GitLab