aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMITSUNARI Shigeo <herumi@nifty.com>2018-11-27 14:52:19 +0800
committerMITSUNARI Shigeo <herumi@nifty.com>2018-11-27 14:52:19 +0800
commit5c8dad4f5e16500e697d43964a67790b34dfd230 (patch)
tree94b830367f4f40ce9fc227ebef7144513181b294
parenta7efe8a6fee268f2c12da379c8fed7ef81673e84 (diff)
downloadtangerine-mcl-5c8dad4f5e16500e697d43964a67790b34dfd230.tar.gz
tangerine-mcl-5c8dad4f5e16500e697d43964a67790b34dfd230.tar.zst
tangerine-mcl-5c8dad4f5e16500e697d43964a67790b34dfd230.zip
add Array::operator= if exception is enable
-rw-r--r--include/mcl/array.hpp25
-rw-r--r--test/array_test.cpp27
2 files changed, 46 insertions, 6 deletions
diff --git a/include/mcl/array.hpp b/include/mcl/array.hpp
index 84c5f37..a6d2a8f 100644
--- a/include/mcl/array.hpp
+++ b/include/mcl/array.hpp
@@ -8,6 +8,9 @@
*/
#include <stdlib.h>
#include <stddef.h>
+#ifndef CYBOZU_DONT_USE_EXCEPTION
+#include <new>
+#endif
namespace mcl {
@@ -15,8 +18,6 @@ template<class T>
class Array {
T *p_;
size_t n_;
- Array(const Array&);
- void operator=(const Array&);
template<class U>
void swap_(U& x, U& y) const
{
@@ -31,6 +32,26 @@ public:
{
free(p_);
}
+#ifndef CYBOZU_DONT_USE_EXCEPTION
+ Array(const Array& rhs)
+ : p_(0)
+ , n_(0)
+ {
+ if (rhs.n_ == 0) return;
+ p_ = (T*)malloc(sizeof(T) * rhs.n_);
+ if (p_ == 0) throw std::bad_alloc();
+ n_ = rhs.n_;
+ for (size_t i = 0; i < n_; i++) {
+ p_[i] = rhs.p_[i];
+ }
+ }
+ Array& operator=(const Array& rhs)
+ {
+ Array tmp(rhs);
+ tmp.swap(*this);
+ return *this;
+ }
+#endif
bool resize(size_t n)
{
if (n <= n_) {
diff --git a/test/array_test.cpp b/test/array_test.cpp
index d9b66c7..2168a28 100644
--- a/test/array_test.cpp
+++ b/test/array_test.cpp
@@ -1,14 +1,19 @@
#include <mcl/array.hpp>
#include <cybozu/test.hpp>
+template<class Array, size_t n>
+void setArray(Array& a, const int (&tbl)[n])
+{
+ CYBOZU_TEST_ASSERT(a.resize(n));
+ for (size_t i = 0; i < n; i++) a[i] = tbl[i];
+}
+
template<class Array, size_t an, size_t bn>
void swapTest(const int (&a)[an], const int (&b)[bn])
{
Array s, t;
- CYBOZU_TEST_ASSERT(s.resize(an));
- CYBOZU_TEST_ASSERT(t.resize(bn));
- for (size_t i = 0; i < an; i++) s[i] = a[i];
- for (size_t i = 0; i < bn; i++) t[i] = b[i];
+ setArray(s, a);
+ setArray(t, b);
s.swap(t);
CYBOZU_TEST_EQUAL(s.size(), bn);
CYBOZU_TEST_EQUAL(t.size(), an);
@@ -83,3 +88,17 @@ CYBOZU_TEST_AUTO(FixedArray)
swapTest<mcl::FixedArray<int, n> >(aTbl, bTbl);
swapTest<mcl::FixedArray<int, n> >(bTbl, aTbl);
}
+
+#ifndef CYBOZU_DONT_USE_EXCEPTION
+CYBOZU_TEST_AUTO(assign)
+{
+ const int aTbl[] = { 3, 4, 2 };
+ const int bTbl[] = { 3, 4, 2, 1, 5 };
+ mcl::Array<int> a, b;
+ setArray(a, aTbl);
+ setArray(b, bTbl);
+ a = b;
+ CYBOZU_TEST_EQUAL(a.size(), b.size());
+ CYBOZU_TEST_EQUAL_ARRAY(a.data(), b.data(), a.size());
+}
+#endif