Storing each element of a container class as an object
Recently, I have seen some Matrix and 1D array classes implemented in C++ where each individual element is wrapped as a class (e.g. Element class). Normally, we like to have containers like Matrix to contain actual elements (e.g. 开发者_运维问答int) consecutive in a memory. Using a custom class for individual elements can give you some flexibility but what are the possible drawbacks? To make it short, see the pseudo-code:
// 1st approach: Elements stored in their type.
template <class T>
class Matrix
{
T *m_data;
//..
};
// 2nd approach: Elements wrapped into a class
template<class T>
class Matrix
{
std::set<Element<T> > m_data; // or using std::vector<Element<T> > m_data
//..
}; // Element is a class representing single element of type T
what could be the implications of this second approach, specially if we need to use Matrix for large amount of data? Also, if we need to use this type with GPU programming(transfering to device memory back and forth)?
One drawback is a memory cost for each Element, which could be a performance concern in large collections. It will cost you at least a byte, probably more for the padding. The "sizeof" operator should tell you the cost.
If the class has no virtual functions, they will probably* be placed in contiguous memory with something like new Element[20]
or std::vector<Element> v(20)
. As noted above, std::set and most other STL containers are not necessarily contiguous.
*I say "probably" because depending on the size of the actual type, the compiler might insert some padding, which you can probably control with #pragmas as needed.
精彩评论