实施深度复制
我试图在通用指针数组上实现深层复制。 我一直在争取这2 +天,并不能为我的生活弄清楚!
有一个由我的教授提供的相关测试程序,但我不认为这是需要的。 至于实现。 在代码中查看下面的选项...
选项1:扁平测试失败,这是一个浅的副本。
选项2:产生段错误,我不明白为什么我只是取消引用指针。
选项3:再次通过测试。 它是一个浅拷贝?
选项4:我甚至无法编译,但我希望分配一个新的元素,只是从原来的位复制。 编译器喋喋不休地把一个poiter变成一个类型,而不是某种类型或某种东西。 所以我在sizeof(*element)
对它进行了解引用,然后它说了一些关于主表达式的内容。
我在这里错过了什么,我明白深层复制与浅层复制是什么。 您不需要复制实体,而需要创建新的对象,并将新的字段指向与原始值相同的对象。
有没有什么明显的我失踪或者我的企图逻辑真的有什么问题吗? 我该如何解决它?
virtual ConcreteArray<element> *makeDeepCopy() const
{
ConcreteArray* arrayPtr = new ConcreteArray();
int option = 4;
for (size_t index = 0; index < this->size(); ++index)
{
switch (option)
{
case 1:
{
arrayPtr->push_back(*new element);
arrayPtr->at(index) = this->at(index);
break;
}
case 2:
{
arrayPtr->push_back(*new element);
*arrayPtr->at(index) = *this->at(index);
break;
}
case 3:
{
element* E = new element;
*E = this->at(index);
arrayPtr->push_back(*E);
break;
}
case 4:
{
arrayPtr->push_back(*new element);
memcpy(this->at(index), arrayPtr->back(), sizeof(element));
}
default: return nullptr;
}
}
return arrayPtr;
}
有关其他信息,这里是构造函数...
template<class element>
class ConcreteArray : public Array<element>
{
private:
/// Default capacity is an arbitrary small value > 0
static const size_t defaultCapacity = 8;
element *m_Data; /// Pointer to storage for elements
size_t m_Size; /// Number of elements stored
size_t m_Capacity; /// Number of elements that can be
public:
////////////////////////////////////////////////////////
/// Default constructor
ConcreteArray() :
m_Size(0),
m_Capacity(ConcreteArray::defaultCapacity)
{
m_Data = new element[m_Capacity];
};
////////////////////////////////////////////////////////
/// Copy Constructor (shallow copy)
ConcreteArray(const ConcreteArray<element> &original) :
m_Size(original.m_Size),
m_Capacity(original.m_Capacity)
{
assert(m_Size <= m_Capacity);
m_Data = new element[m_Capacity];
for(size_t i = 0; i < m_Size; i++)
{
m_Data[i] = original.m_Data[i];
}
};
还有我调用的函数,不包括memcpy()...
////////////////////////////////////////////////////////
/// Returns the number of elements in array
virtual size_t size() const
{
return m_Size;
};
////////////////////////////////////////////////////////
/// Append element at end of array expanding storage for
/// array as necessary
void push_back(element const &anElement)
{
this->insertAt(anElement, this->size());
};
////////////////////////////////////////////////////////
/// The array is extended by inserting element before
/// the element at the specified index increasing the
/// array size by 1.
/// Any existing elements at index and beyond are moved
/// to make space for the inserted element.
/// If index is equal to size(), element is appended to
/// the end of the array.
/// Array storage expands as necessary.
virtual void insertAt(element const &anElement,
size_t index)
{
assert(index <= m_Size);
if(m_Size == (m_Capacity - 1))
{ // Double the amount of memory allocated for
// storing elements
m_Capacity *= 2;
element *newData = new element[m_Capacity];
for(size_t i = 0; i < m_Size; i++)
{
newData[i] = m_Data[i];
}
delete [] m_Data;
m_Data = newData;
}
assert((m_Size + 1) < m_Capacity);
if(index < m_Size)
{ // Move elements after index to make room for
// element to be inserted
for(size_t i = m_Size - 1; i > index; i--)
{
m_Data[i] = m_Data[i-1];
}
}
m_Size++;
m_Data[index] = anElement;
};
////////////////////////////////////////////////////////
/// Returns the element at index
virtual element const &at(size_t index) const
{
assert(index < m_Size);
return m_Data[index];
};
////////////////////////////////////////////////////////
/// Returns the element at index
virtual element &at(size_t index)
{
assert(index < m_Size);
return m_Data[index];
};
基本模板类...
//
// Array.h
// Project1
//
#ifndef __Array__Array
#define __Array__Array
#include <stdlib.h> // For size_t
#include <iostream> // std::cout
#include <iterator> // std::iterator, std::input_iterator_tag
#include <sstream>
#include <string>
///////////////////////////////////////////////////////////
/// This class encapsulates an array storing any number of
/// elements limited only by the amount of memory available
/// in the host process and provides access to stored
/// elements via within the array.
template<typename element>
class Array
{
public:
///
/// Virtual Destructor
virtual ~Array() {};
///////////////////////////////////////////////////////////
/// BEGIN Pure virtual member functions to be implemented
/// by concrete subclasses
///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/// These member functions each return an iterator to
/// the first element in the array.
virtual element * begin() = 0;
virtual const element * begin() const = 0;
////////////////////////////////////////////////////////
/// These member functions each return an iterator to
/// one index past the end of the array.
virtual element * end() = 0;
virtual const element * end() const = 0;
////////////////////////////////////////////////////////
/// The array is extended by inserting anElement before
/// the element at the specified index increasing the
/// array size by 1. Any existing elements at index
/// and beyond are moved to make space for the inserted
/// element.
/// If index is equal to size(), anElement is appended to
/// the end of the array. Array storage expands as
/// necessary.
virtual void insertAt(element const &anElement,
size_t index) = 0;
////////////////////////////////////////////////////////
/// Remove element at index from array moving all
/// elements after index down one position to fill gap
/// created by removing the element reducing the array
/// size by 1
virtual void removeAt(size_t index) = 0;
////////////////////////////////////////////////////////
/// Returns the number of elements in array
virtual size_t size() const = 0;
////////////////////////////////////////////////////////
/// Sets the element value stored at the specified
/// index. works as long index is less than size().
virtual void setAt(element const &anElement,
size_t index) = 0;
////////////////////////////////////////////////////////
/// Returns a reference to the element at index
virtual element const &at(size_t index) const = 0;
////////////////////////////////////////////////////////
/// Returns a reference to the element at index
virtual element &at(size_t index) = 0;
///////////////////////////////////////////////////////////
/// END Pure virtual member functions to be implemented
/// by concrete
///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/// Remove all elements from array and set array's size
/// to 0
void clear()
{
while(0 < this->size())
{
this->pop_back();
}
};
element &back()
{
return at(size() - 1);
}
element const &back() const
{
return at(size() - 1);
}
////////////////////////////////////////////////////////
/// Append element at end of array expanding storage for
/// array as necessary
void push_back(element const &anElement)
{
this->insertAt(anElement, this->size());
};
////////////////////////////////////////////////////////
/// Removes and returns the last element in array
void pop_back()
{
assert(0 < this->size());
this->removeAt(this->size() - 1);
};
////////////////////////////////////////////////////////
/// Appends all elements in a Array to array expanding
/// storage for array as necessary
void append(Array &source)
{
const size_t count = source.size();
for(size_t i = 0; i < count; i++)
{
this->push_back(source.at(i));
}
};
////////////////////////////////////////////////////////
/// Returns a reference to the element at index. This
/// operator enables semantics similar to built-in
/// arrays. e.g.
/// someArray[5] = someArray[6];
element &operator [](size_t index)
{
return this->at(index);
}
////////////////////////////////////////////////////////
/// Returns a reference to the element at index. This
/// operator enables semantics similar to built-in
/// arrays. e.g.
/// someArray[6];
element const &operator [](size_t index) const
{
return this->at(index);
}
////////////////////////////////////////////////////////
/// Returns a string representation of the array's
/// elements
operator std::string() const
{
std::ostringstream tempOStream;
tempOStream << "(";
std::copy(begin(), end(),
std::ostream_iterator<void *>(tempOStream, ", "));
tempOStream << ")n";
return tempOStream.str();
}
};
#endif /* defined(__Arrayy__Array__) */
还有扩展类
//
// ConcreteArray.h
// Project1
//
//
#ifndef __Array__ConcreteArray__
#define __Array__ConcreteArray__
#include "Array.h"
#include <string.h> // For memmove()
#include <stdlib.h> // For calloc(), realloc()
#include <algorithm>
#include <assert.h>
#include <iterator> // std::iterator, std::input_iterator_tag
///////////////////////////////////////////////////////////
/// BEGIN code added for Project 3
///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
// THIS FUNCTION MUST BE DECLARED BEFORE
// ConcreteArray OR ELSE COMPILER WILL NOT KNOW HOW
// TO COPY elements.
////////////////////////////////////////////////////////
template<typename T>
T *deepCopy(T *original)
{
return original->makeDeepCopy();
}
////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
// THIS FUNCTION MUST BE DECLARED BEFORE
// ConcreteArray OR ELSE COMPILER WILL NOT KNOW HOW
// TO COPY long *.
////////////////////////////////////////////////////////
long *deepCopy(long *original)
{
return new long(*original);
}
///////////////////////////////////////////////////////////
/// END code added for Project 3 (SEE THE
/// Project 3 "To Do" CODE BELOW
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/// This class encapsulates an array storing any number of
/// elements limited only by the amount of memory available
/// in the host process and provides access to stored
/// elements via index position within the array.
template<class element>
class ConcreteArray : public Array<element>
{
private:
/// Default capacity is an arbitrary small value > 0
static const size_t defaultCapacity = 8;
element *m_Data; /// Pointer to storage for elements
size_t m_Size; /// Number of elements stored
size_t m_Capacity; /// Number of elements that can be
public:
////////////////////////////////////////////////////////
/// Default constructor
ConcreteArray() :
m_Size(0),
m_Capacity(ConcreteArray::defaultCapacity)
{
m_Data = new element[m_Capacity];
};
////////////////////////////////////////////////////////
/// Copy Constructor (shallow copy)
ConcreteArray(const ConcreteArray<element> &original) :
m_Size(original.m_Size),
m_Capacity(original.m_Capacity)
{
assert(m_Size <= m_Capacity);
m_Data = new element[m_Capacity];
for(size_t i = 0; i < m_Size; i++)
{
m_Data[i] = original.m_Data[i];
}
};
////////////////////////////////////////////////////////
/// Destructor
virtual ~ConcreteArray()
{
delete [] m_Data;
m_Size = 0;
};
////////////////////////////////////////////////////////
/// The array is extended by inserting element before
/// the element at the specified index increasing the
/// array size by 1.
/// Any existing elements at index and beyond are moved
/// to make space for the inserted element.
/// If index is equal to size(), element is appended to
/// the end of the array.
/// Array storage expands as necessary.
virtual void insertAt(element const &anElement,
size_t index)
{
assert(index <= m_Size);
if(m_Size == (m_Capacity - 1))
{ // Double the amount of memory allocated for
// storing elements
m_Capacity *= 2;
element *newData = new element[m_Capacity];
for(size_t i = 0; i < m_Size; i++)
{
newData[i] = m_Data[i];
}
delete [] m_Data;
m_Data = newData;
}
assert((m_Size + 1) < m_Capacity);
if(index < m_Size)
{ // Move elements after index to make room for
// element to be inserted
for(size_t i = m_Size - 1; i > index; i--)
{
m_Data[i] = m_Data[i-1];
}
}
m_Size++;
m_Data[index] = anElement;
};
////////////////////////////////////////////////////////
/// Remove element at index from array moving all
/// elements after index one position to fill gap
/// created by removing the element
virtual void removeAt(size_t index)
{
assert(index < m_Size);
if((index + 1) < m_Size)
{ // Move elements to close gap left by removing
// an element
for(size_t i = index + 1; i < m_Size; i++)
{
m_Data[i-1] = m_Data[i];
}
}
m_Size--;
};
////////////////////////////////////////////////////////
/// Returns the number of elements in array
virtual size_t size() const
{
return m_Size;
};
////////////////////////////////////////////////////////
/// Sets the element value stored at the specified
/// index. works as long index is less than size().
virtual void setAt(element const &anElement,
size_t index)
{
assert(index < m_Size);
m_Data[index] = anElement;
};
////////////////////////////////////////////////////////
/// Returns the element at index
virtual element const &at(size_t index) const
{
assert(index < m_Size);
return m_Data[index];
};
////////////////////////////////////////////////////////
/// Returns the element at index
virtual element &at(size_t index)
{
assert(index < m_Size);
return m_Data[index];
};
///////////////////////////////////////////////////////////
/// BEGIN code added for Project 3
///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
/// Constructor via iterators (shallow copy)
template <class _InputIterator>
ConcreteArray(
_InputIterator start,
_InputIterator end) :
m_Size(0),
m_Capacity(ConcreteArray::defaultCapacity)
{
m_Data = new element[m_Capacity];
for(_InputIterator it(start); it != end; ++it)
{
this->push_back(*it);
}
}
////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
/// Returns a newly allocated array produced by deep
/// copying this.
virtual ConcreteArray<element> *makeDeepCopy() const
{
//////////////////////////////////////
/// ***** TO DO *****
/// Implement deep copy logic here!
//////////////////////////////////////
ConcreteArray* arrayPtr = new ConcreteArray();
int option = 5;
for (size_t index = 0; index < this->size(); ++index)
{
switch (option)
{
case 1:
{
arrayPtr->push_back(*new element);
arrayPtr->at(index) = this->at(index);
break;
}
case 2:
{
arrayPtr->push_back(*new element);
*arrayPtr->at(index) = *this->at(index);
break;
}
case 3:
{
element* E = new element;
*E = this->at(index);
arrayPtr->push_back(*E);
break;
}
case 4:
{
arrayPtr->push_back(*new element);
//memcpy(this->at(index), arrayPtr->back(), sizeof(element));
}
case 5:
{
element* aNewElementPtr = new element;
element origElementPtr = at(index);
*aNewElementPtr = origElementPtr;
}
default: return nullptr;
}
}
return arrayPtr;
}
////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
/// These member functions each return an iterator to
/// the first element in the array.
virtual element * begin()
{
//return nullptr; // Replace this line
return m_Data;
};
////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
virtual const element * begin() const
{
//return nullptr; // Replace this line
return m_Data;
};
////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
/// These member functions each return an iterator to
/// one index past the end of the array.
virtual element * end()
{
//return nullptr; // Replace this line
return m_Data + m_Size;
};
////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
virtual const element * end() const
{
//return nullptr; // Replace this line
return m_Data + m_Size;
};
////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
/// Overloaded assignment operator
ConcreteArray &operator=(
const ConcreteArray &original)
{
if (this != &original) // protect against invalid self-assignment
{
//////////////////////////////////////
/// ***** TO DO *****
/// Implement deep copy logic here!
//////////////////////////////////////
return *original.makeDeepCopy();
}
return *this;
}
};
////////////////////////////////////////////////////////
/// NEW IN PROJECT 3
////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////
template<typename T>
ConcreteArray<T> *deepCopy(ConcreteArray<T> *original)
{
return original->makeDeepCopy();
}
#endif /* defined(__Array__ConcreteArray__) */
使用与原始缓冲区大小相同的新阵列。
对于每个相应的元素对,调用lhs_element = deepCopy(rhs_element)
,其中lhs_element是新数组中的元素,rhs_element是原始数组中的元素。