Here are some examples:
Code:
Before using std::vector:
#include <iostream>
int * getArray(){
return new int[25];
}
int main(){
int * arr = getArray();
for (int i = 0; i < 25; i++)
arr[i] = i * 2;
for (int i = 0; i < 25; i++)
std::cout << "[" << arr[i] << "]";
delete[] arr;
}
After using std::vector:
#include <iostream>
#include <vector>
typedef std::vector<int> intArray;
intArray getArray(){
return intArray(25);
}
int main(){
intArray arr = getArray();
for (int i = 0; i < 25; i++)
arr[i] = i * 2;
for (int i = 0; i < 25; i++)
std::cout << "[" << arr[i] << "]";
}
For single objects, you can use std::auto_ptr (NOT CONTAINER SAFE) or download Boost and use boost::shared_ptr (container safe). One example:
Code:
Before using a smart pointer:
#include <iostream>
struct Point{
int x;
int y;
};
Point * getPoint(){
return new Point;
}
int main(){
Point * p = getPoint();
p->x = 3;
p->y = 11;
std::cout << "(" << p->x << ", " << p->y << ")" << std::endl;
delete p;
}
After using a smart pointer:
#include <iostream>
#include <memory>
struct Point{
int x;
int y;
};
typedef std::auto_ptr<Point> pointPtr;
pointPtr getPoint(){
return pointPtr(new Point); //Note how we wrap a call to new inside a constructor for the auto_ptr
}
int main(){
pointPtr p = getPoint();
p->x = 3;
p->y = 11;
std::cout << "(" << p->x << ", " << p->y << ")" << std::endl;
}
Hope that helps. The examples are contrived, but should illustrate usage.