I've started learning C++ recently and want from what I've gathered smart pointers are the way to go when storing stuff on the free store. I want to make sure I've got the basic hang of C++(11) correctly. I've implemented a very basic vector class (a mathematical vector) and would greatly appreciate if anyone would point out if I'm doing something wrong or that could be done better.
Vector.h
#ifndef VECTOR
#define VECTOR
#include <memory>
class Vector {
private:
int x;
int y;
int z;
public:
Vector(int x, int y, int z);
~Vector();
std::unique_ptr<Vector> operator + (Vector* vector);
int GetX() { return x; }
int GetY() { return y; }
int GetZ() { return z; }
void SetX(int x) { this->x = x; }
void SetY(int y) { this->y = y; }
void SetZ(int z) { this->z = z; }
};
#endif
Vector.cpp
#include <memory>
#include <iostream>
#include "Vector.h"
Vector::Vector(int x, int y, int z) : x(x), y(y), z(z) {
std::cout << "Constructed a Vector instance with elements ( " << x << ", " << y << "," << z << " )." << std::endl;
};
Vector::~Vector() {
std::cout << "Destructed a Vector instance with elements ( " << x << ", " << y << "," << z << " )." << std::endl;
}
std::unique_ptr<Vector> Vector::operator + (Vector* vector) {
std::unique_ptr<Vector> result = std::make_unique<Vector>(0, 0, 0);
result->SetX(this->x + vector->GetX());
result->SetY(this->y + vector->GetY());
result->SetZ(this->z + vector->GetZ());
return result;
};
Usage
#include <iostream>
#include <memory>
#include "Vector.h"
int main() {
std::unique_ptr<Vector> v1 = std::make_unique<Vector>(1, 2, 3);
std::unique_ptr<Vector> v2 = std::make_unique<Vector>(3, 2, 1);
std::unique_ptr<Vector> vr = *(v1.get()) + v2.get();
}
When using the overloaded operator (+) it looks a bit ugly but it's the way I found that worked when using unique_ptr<T>
. One thing I'm doubting if I'm doing "correctly" is returning a unique_ptr<T>
. Should I return a value instead and then create a unique_ptr<T>
from that instead?