Strange execution behavior..

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I was asked by a colleague about the code given below.
I compiles and runs as:
 1. No errors on: AMD64 based Solaris-10 (g++: 3.4.3)
 2. Buserror on SPARC based Solaris-10 (g++: 3.4.4)
    after printing the results..
 3. Segmentation fault on Linux (g++: 4.1.2) after
    printing the results..

Any pointers will be appreciated.
-ishwar
--------
/////////////////////////////////////////////////////////
//
// sptr.cc
//
// A. Ugur, March 20, 2007
//
// to compile: g++ sptr.cc -o sptr
//
/////////////////////////////////////////////////////////

#include <iostream>
//#include <cmath>

class Node
{
public:
  int x, y;  // alignment coordinates

public:
  Node();
  Node(int i, int j);
};

Node::Node()
// default constructor
{
  x = -1;
  y = -1;
}

Node::Node(int i, int j)
// parameterized constructor
{
  x = i;
  y = j;
}

template<class T> class smartPtr
{
  T* p;

public:
  smartPtr();
  smartPtr(T& n);
  T* operator->();
};

template<class T>
smartPtr<T>::smartPtr()
// default constructor
{
  *p = T();
}

template<class T>
smartPtr<T>::smartPtr(T& n)
// parameterized constructor
{
  p = &n;
}

template<class T>
T* smartPtr<T>::operator->()
// overloaded operator->()
{
  return p;
}


// function to use smartpointer to Node object
void f(smartPtr<Node> p, int i, int j)
{
  p->x = i;
  p->y = j;
}

// test driver for smartpointer
main(int argc, char* argv[])
{

  Node n1, n2, n3(3, 3);
  smartPtr<Node> p;

  printf("n1: after constructor: (%d,%d)\n", n1.x, n1.y);
  printf("n2: after constructor: (%d,%d)\n", n2.x, n2.y);
  printf("n3: after constructor: (%d,%d)\n", n3.x, n3.y);

  p = smartPtr<Node>(n3);

  f(p, 5, 5);

  printf("n3: after f applied: (%d,%d)\n", n3.x, n3.y);

}
---

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux