Deep analysis of CArray classes in MFC

Source: Internet
Author: User
Tags arrays data structures

When we use VC for more complex programming, we often need to use complex array structure, and hope to implement dynamic management. Because C + + does not support dynamic arrays, MFC provides a CArray class to implement the functionality of a dynamic array. Effective use of the CArray class, can improve the efficiency of the program.
MFC provides a set of template libraries to implement some of the more common data structures such as ARRAY,LIST,MAP. CArray is one of them, used to implement the function of the dynamic array.

CArray is derived from CObject, has two template parameters, the first argument is the variable type of the CArray class array element, and the latter is the parameter type when the function is called.

We have a class object, we want to define a dynamic array of Object, then we can use the following two ways:

CArray<Object,Object> Var1;
CArray<Object,Object&> Var2;

Var1 and Var2 which one of the efficiency is high? The efficiency of VAR2 is high. Why, then? Next we do an analysis on the source code of CArray is clear.

Let's take a look at the member variables and their effects in CArray.

TYPE* m_pData;  // 数据保存地址的指针
int m_nSize;    // 用户当前定义的数组的大小
int m_nMaxSize;  // 当前实 际分配的数组的大小
int m_nGrowBy;  // 分配内存时增长的元素个数

First look at its constructor, initialize the member variable.

CArray<TYPE, ARG_TYPE>::CArray()
{
  m_pData = NULL;
  m_nSize = m_nMaxSize = m_nGrowBy = 0;
}

SetSize member functions are used to allocate space for arrays, starting here to see how the CArray manages the data. The SetSize function is defined as follows:

void SetSize( int nNewSize, int nGrowBy = -1 );

Nnewsize Specify the size of the array

Ngrowby the number of elements to increase if you need to increase the size of the array.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.