Home > programming > DsStack Copy Constructor: Optimized!

DsStack Copy Constructor: Optimized!

Ok so I optimized the DsStack class in multiple ways.

Firstly, I re-wrote the default constructor and the SNode constructor:

 *Made data pass by reference as opposed to by value
 *and made it const
 *Made next const
SNode::SNode(const DString& data, const SNode* next)
                   : data(data), next((SNode*)next){

Stack::Stack(void) : top(NULL) {

As you may have noticed, most variables are initialized via initialization list. This is to optimize performance; it also happens to save lines 😉

I’ve made the copy constructor as well:

Stack::Stack(const Stack& src) : top(NULL) {
  if (&src != this) {
    SNode* prev(NULL);
    SNode* cur(NULL);

    for (SNode* srcCur(src.top);
          srcCur != NULL;
          srcCur = srcCur->next) {
      cur = new SNode(srcCur->data);
      if (prev != NULL)
        prev->next = cur;
        top = cur;
      prev = cur;

You’ll notice that this constructor uses initialization lists extensively. As well, I’ve tried to limit the creation of new objects as much as possible. That’s about it.


  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: