More effective C + +: Do not use polymorphic arrays

Source: Internet
Author: User

The most important feature of class inheritance is that you can manipulate derived classes through base class pointers or references. Such pointers or references have polymorphism of behavior, as if they have multiple forms at the same time. C + + allows you to manipulate derived class arrays through base class pointers and references. This is not an attribute at all, because such code does not work as you wish.

Suppose you have a class BST (for example, a search tree object) and a derived class Balancedbst that inherits from the BST class:

class BST { ... };
class BalancedBST: public BST { ... };

In a real-world program, such a class should be a template class, but in this case it doesn't matter, and a template just makes the code harder to read. For ease of discussion, let's assume that BST and balancedbst contain only int type data.

There is a function that prints the contents of each BST object in an array of BST classes:

void printBSTArray(ostream& s,
const BST array[],
int numElements)
{
 for (int i = 0; i < numElements; ) {
  s << array[i]; //假设BST类
 } //重载了操作符<<
}

When you pass to the function an array variable containing the BST object, it works correctly:

BST BSTArray[10];
...
printBSTArray(cout, BSTArray, 10); // 运行正常

Consider, however, what happens when you pass an array variable that contains a Balancedbst object to the Printbstarray function:

BalancedBST bBSTArray[10];
...
printBSTArray(cout, bBSTArray, 10); // 还会运行正常么?

Your compiler will compile this function without warning, but take a look at the looping code for this function:

for (int i = 0; i < numElements; ) {
 s << array[i];
}

Here the array[i] is just an abbreviation of a pointer algorithm: it represents a * (array). We know that array is a pointer to the starting address of an array, but what is the interval between the memory address of each element in the array and the starting address of the array? Their interval is i*sizeof (an object in an array) because there is an I object between array [0] and [i]. The compiler must be able to determine the size of the objects in the array in order to establish the correct execution code for traversing the array, which is easy for the compiler to do. The parameter array is declared as a BST type, so each element in the array is a BST type, so the interval between each element and the starting address of the array is be i*sizeof (BST).

At least your compiler thinks so. But if you pass an array variable containing a Balancedbst object to the Printbstarray function, your compiler will make a mistake. In this case, the compiler originally assumed that the elements in the array were the same size as the BST object, but now each object in the array is the same size as the BALANCEDBST. The length of a derived class is usually longer than the base class. We expect the length of the Balancedbst object to be longer than the BST. If so, the pointer algorithm generated by the Printbstarray function would be wrong, and no one would know what would happen if the Printbstarray function was executed with an BALANCEDBST array. No matter what the consequences are unpleasant.

If you try to delete an array that contains derived class objects, a variety of problems will occur. Here's a way you might be wrong.

//删除一个数组, 但是首先记录一个删除信息
void deleteArray(ostream& logStream, BST array[])
{
 logStream << "Deleting array at address "
 << static_cast(array) << '
';
 delete [] array;
}
BalancedBST *balTreeArray = // 建立一个BalancedBST对象数组
new BalancedBST[50];
...
deleteArray(cout, balTreeArray); // 记录这个删除操作

It also hides the pointer algorithm you can't see. When an array is deleted, the destructor of each array element is also invoked. When the compiler encounters such code:

delete [] array;

It certainly generates code like this:

// 以与构造顺序相反的顺序来
// 解构array数组里的对象
for ( int i = 数组元素的个数 1; i >= 0;--i)
{
 array[i].BST::~BST(); // 调用 array[i]的
} // 析构函数

Because the loop statement you write cannot be running at all, it will not work correctly when compiled into executable code. The language specification says that by using a base-class pointer to delete an array containing derived class objects, the result is indeterminate. This actually means that executing such code is certainly not going to be a good result. Polymorphic and pointer algorithms cannot be mixed together, so arrays and polymorphism cannot be used together.

It is important to note that if you do not derive another specific class (such as Balancedbst) from a specific class (such as BST), then you are less likely to make the error of using polymorphic arrays (concrete classes). As explained in article 33, which I will introduce later, there are many benefits to not deriving specific classes from specific classes.

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.