How to fix this C++ Memory Management? - c++

I want to build a Memory Management to avoid memory leak but my code has an error that I have no idea how to fix, and how to fix the error in the code?
There: EMC_DELETE cls2; // <-- error: expected a ';'
This code is referenced from a GLSL parser (https://github.com/graphitemaster/glsl-parser/blob/main/ast.h).
// A helper function to help other to reproduce the same example.
std::string pathFolderOrFileName(const std::string &path) {
return path.substr(path.find_last_of("/\\") + 1);
}
template <typename T>
static inline void _destroy(void *self) {
((T*)self)->~T();
free(self);
}
struct Memory {
// Memory Management that's referenced from "emc-language > lexer-parser > ast.h".
Memory() : data(0), dtor(0) { }
template <typename T>
Memory(T *data, const char *file, int line) :
data((void*)data),
dtor(&_destroy<T>),
file(file),
line(line)
{}
void *data;
void (*dtor)(void*);
const char *file;
int line;
void destroy() {
dtor(data);
}
};
template <typename T>
struct Node {
void *operator new(size_t size, std::vector<Memory> *collector, const char *file, int line) throw() {
void *data = malloc(size);
if (data) {
collector->push_back(Memory((T *)data, file, line));
}
return data;
}
void operator delete(void *data, std::vector<Memory> *collector) {
auto &vec = *collector;
for (int i = 0; i < vec.size(); i++) {
if (vec[i].data == data) {
vec.erase(vec.begin() + i);
free(data);
return;
}
}
assert(0);
}
};
// Note: Never use the default 'operator new & delete' because they can cause memory leak.
#define EMC_NEW new(&g_memory, __FILE__, __LINE__) // Use this instead of using the default 'operator new'.
#define EMC_DELETE delete(&g_memory) // Use this instead of using default 'operator delete'.
//----------------------------------------------------------------------------------------------------
class MyBaseClass {
public:
int base_x, base_y;
};
class MyClass : public Node<MyClass> {
public:
int x, y;
MyClass() {
}
~MyClass() {
}
};
std::vector<Memory> g_memory;
int main() {
MyClass *cls0 = EMC_NEW MyClass();
MyClass *cls1 = EMC_NEW MyClass();
MyClass *cls2 = EMC_NEW MyClass();
EMC_DELETE cls2; // <-- error: expected a ';'
for (int i = 0; i < g_memory.size(); i++) {
auto &it = g_memory[i];
printf("%d: (file \"%s\", line %d)\n", i, pathFolderOrFileName(it.file).c_str(), it.line);
}
return 0;
}
Expected output:
0: (file "test_draft.cpp", line 79)
1: (file "test_draft.cpp", line 80)
2: (file "test_draft.cpp", line 81) this line must be removed because cls2 must be deleted.

Related

c++ can not get value from map

I have implemented a serializer to send data over network. And I have implemented a system that can deserialize primitive data, string, map(string, string), map(string, float), but the error happens with map(string, int) when the deserialized map is used to fetch the value from key. In the debugger I can see that map receive correct value but when I'm trying to get data, I get an error "std::out_of_range at memory location".
Here is my code
#include <stdint.h>
#include <memory>
#include <string>
#include <map>
#include <algorithm>
#define STREAM_ENDIANNESS 0
#define PLATFORM_ENDIANNESS 0
using namespace std;
class OutputMemoryStream
{
void ReallocBuffer(uint32_t inNewLength)
{
mBuffer = static_cast<char*>(std::realloc(mBuffer, inNewLength));
mCapacity = inNewLength;
}
char* mBuffer = nullptr;
uint32_t mHead;
uint32_t mCapacity;
public:
OutputMemoryStream() : mHead(0) { ReallocBuffer(32); }
~OutputMemoryStream()
{
if (mBuffer) { mBuffer = nullptr; }
}
char* GetBufferPtr() const { return mBuffer; }
uint32_t GetLength() const { return mHead; }
void Write(const void* inData, size_t inByteCount)
{
//make sure we have space...
uint32_t resultHead = mHead + static_cast<uint32_t>(inByteCount);
if (resultHead > mCapacity)
{
ReallocBuffer(std::max(mCapacity * 2, resultHead));
}
//copy into buffer at head
std::memcpy(mBuffer + mHead, inData, inByteCount);
//increment head for next write
mHead = resultHead;
}
template< typename T > void Write(T inData)
{
static_assert(std::is_arithmetic< T >::value || std::is_enum< T >::value, "Generic Write only supports primitive data types");
if (STREAM_ENDIANNESS == PLATFORM_ENDIANNESS)
{
Write(&inData, sizeof(inData));
}
else { }
}
template< typename T >
void Write(const std::map< string, T >& inMap)
{
uint32_t elementCount = inMap.size();
Write(elementCount);
for (std::pair<string, T> element : inMap)
{
Write(element.first);
Write(element.second);
}
}
void Write(const std::string& inString)
{
size_t elementCount = inString.size();
Write(elementCount + 1);
Write(inString.data(), (elementCount + 1) * sizeof(char));
}
};
class InputMemoryStream
{
private:
char* mBuffer;
uint32_t mHead;
uint32_t mCapacity;
public:
InputMemoryStream() {}
InputMemoryStream(char* inBuffer, uint32_t inByteCount) : mBuffer(inBuffer), mCapacity(inByteCount), mHead(0) { }
~InputMemoryStream()
{
if (mBuffer) { mBuffer = nullptr; }
}
uint32_t GetRemainingDataSize() const
{
return mCapacity - mHead;
}
void Read(void* outData, uint32_t inByteCount)
{
uint32_t resultHead = mHead + inByteCount;
if (resultHead > mCapacity)
{
//handle error, no data to read!
//...
}
std::memcpy(outData, mBuffer + mHead, inByteCount);
mHead = resultHead;
}
template< typename T > void Read(T& outData)
{
static_assert(std::is_arithmetic< T >::value || std::is_enum< T >::value, "Generic Read only supports primitive data types");
Read(&outData, sizeof(outData));
}
template<typename T1>
void Read(std::map<string, T1> &mapP)
{
size_t elemenCount;
Read(elemenCount);
for (int i = 0; i < elemenCount; i++)
{
string key; T1 value;
Read(key);
Read(value);
std::pair<string, T1> pair(key, value);
mapP.insert(pair);
}
}
void Read(string &outString)
{
size_t strSize;
Read(strSize);
outString.resize(strSize);
for (int i = 0; i < strSize; i++)
{
Read(&outString[i], 1);
}
}
};
class ServerObject
{
OutputMemoryStream outStream;
InputMemoryStream inStream;
map<std::string, int> mapInt;
public:
ServerObject() {};
ServerObject(char* byteArray, int byteCount)
{
InputMemoryStream inStream(byteArray, byteCount);
Deserialize(inStream);
}
~ServerObject() {};
void Serialize()
{
outStream.Write(mapInt);
}
void Deserialize(InputMemoryStream inStream)
{
inStream.Read(mapInt);
}
OutputMemoryStream GetOutStream()
{
return outStream;
}
int GetInt(string key)
{
return mapInt.at(key);
}
void PutInt(string key, int value)
{
mapInt.insert(std::pair<string, int>(key, value));
}
};
int main()
{
ServerObject * so = new ServerObject();
so->PutInt("test", 10);
so->Serialize();
ServerObject * so1 = new ServerObject(so->GetOutStream().GetBufferPtr(), so->GetOutStream().GetLength());
int i = so1->GetInt("test");
system("pause>NULL");
return 0;
}
Your void Write(const std::string& inString) function of OutputMemoryStream should not store additional byte of buffer for null terminator because std::string will not contain null terminator but if you use c_str(), a null terminator will be included in the return from this method. Don't get confused with the internal structure of the memory. std::string stores the length of the string in its member variable so there is no need of null terminator. The function should be as shown below.
void Write(const std::string& inString)
{
size_t elementCount = inString.size();
Write(elementCount);
Write(inString.data(), elementCount * sizeof(char));
}

Exception Error C++ //Visual Studio [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So im creating an engine from scrath(learnign purposes).
And when i test my TArray i get an Execption thrown in my Memory.h file. This happens only when im trying to test the TArray
Here is my code for TArray.h
#pragma once
#include "Memory/DynamicLinearStackAllocator.h"
template <typename T, typename Allocator = DynamicLinearStackAllocator>
class TArray
{
private:
Allocator m_Allocator;
uint32 m_ElementCount;
public:
FORCEINLINE TArray()
{
}
FORCEINLINE ~TArray()
{
m_Allocator.Destroy();
}
FORCEINLINE TArray(const uint32 InElementCount)
{
m_Allocator.Resize<T>(InElementCount, m_ElementCount);
m_ElementCount = InElementCount;
}
FORCEINLINE void Add(const T &InValue)
{
}
FORCEINLINE T* GetData() const { return m_Allocator.GetAllocator<T>(); }
FORCEINLINE uint32 Num() const
{
return m_ElementCount;
}
FORCEINLINE T& operator[](uint32 InElementIndex) const
{
check(m_ElementCount > InElementIndex);
return GetData()[InElementIndex];
}
};
namespace Tests
{
FORCEINLINE void TestArrays()
{
{
TArray<float> data(10);
check(data.Num() == 10);
for(uint32 i = 0; i < data.Num(); i++)
{
data[i] = 2.0f;
}
check(data[0] == 2.0f);
}
{
TArray<uint32> data(5);
data[0] = 10;
data[1] = 5;
check(data.Num() == 5);
check(data[0] == 10);
check(data[1] == 5);
}
{
TArray<float> data(1);
data[2] = 2.0f;
}
}
}
When i try to compile(Im using Visual Studio 2017) it gives me an execption error at this position in Memory.h
static void* Copy(void *InDestination, const void *InSource, size_t InSize)
{
check_slow(InDestination);
check_slow(InSource);
check_slow(InSize > 0);
return memcpy(InDestination, InSource, InSize);
}
The test is getting called in the main function with this code:
int main()
{
Tests::TestAssertion();
Tests::TestMemory();
Tests::TestAllocator();
Tests::TestArrays();
return 0;
}
my goal currently is to look if the logger shows me the error here:
{
TArray<float> data(1);
data[2] = 2.0f;
}
here is a screenshot of the full error https://gyazo.com/6c1d6779623ffea97504f5b23f9fd7da
edit: here is the code for the allocator
#pragma once
#include <malloc.h>
#include "Core.h"
#define MEMORY_ALIGMENT 16
struct Memory
{
// TODO:Rework types.
static void* Allocate(const int32 InCount, const size_t InSize)
{
check_slow(InCount > 0);
check_slow(InSize > 0);
const size_t size = InSize * InCount;
return _aligned_malloc(size, MEMORY_ALIGMENT);
}
static void Free(void *InBlock)
{
check_slow(InBlock);
_aligned_free(InBlock);
}
static void* Copy(void *InDestination, const void *InSource, size_t InSize)
{
check_slow(InDestination);
check_slow(InSource);
check_slow(InSize > 0);
return memcpy(InDestination, InSource, InSize);
}
};
void* operator new (size_t InSize)
{
return Memory::Allocate(1, InSize);
}
void operator delete (void* InBlock)
{
Memory::Free(InBlock);
}
namespace Tests
{
struct MemoryTestStruct
{
uint32 p0;
uint32 p1;
uint32 p2;
uint32 p3;
};
FORCEINLINE void TestMemory()
{
MemoryTestStruct *t = new MemoryTestStruct();
check(t);
delete t;
}
}
edit2: Here is the code for the StackAlloctor
#pragma once
#include "../Core.h"
class DynamicLinearStackAllocator
{
private:
void *m_Data;
public:
template <typename T>
FORCEINLINE void Resize(const uint32 InElementCount, const uint32 InPreviousElementCount)
{
void *temp = Memory::Allocate(InElementCount, sizeof(T));
if (InPreviousElementCount > 0)
{
const SIZE_T size = sizeof(T) * InPreviousElementCount;
Memory::Copy(temp, m_Data, size);
Memory::Free(m_Data);
}
m_Data = temp;
}
template <typename T>
FORCEINLINE T* GetAllocator() const
{
return (T*)m_Data;
}
FORCEINLINE void Destroy()
{
Memory::Free(m_Data);
}
};
namespace Tests
{
FORCEINLINE void TestAllocator()
{
DynamicLinearStackAllocator alloc;
alloc.Resize<float>(2, 0);
alloc.Destroy();
}
}
You're not showing the code for your Allocator, but the problem is probably this line in your TArray constructor:
m_Allocator.Resize<T>(InElementCount, m_ElementCount);
At this point, m_ElementCount has not been initialized and will have some random value in it. Resize is then probably trying to free up memory that hasn't been allocated (because of the uninitialized value in m_ElementCount). You should pass in a 0 for the second parameter of the Resize call in your constructor
m_Allocator.Resize<T>(InElementCount, 0);
since there is no existing allocated memory to free.
Also, your default constructor for TArray should initialize m_Allocator.m_data to nullptr (or add a default constructor to DynamicLinearStackAllocator to do that) and set m_ElementCount to 0.

Pure virtual function error

I receive this error:
In function 'bool detect_feedback(AudioEffect*)':
54:30: error: cannot convert 'std::shared_ptr<AudioEffect>' to 'AudioEffect*' in assignment
55:16: error: cannot convert 'std::shared_ptr<AudioEffect>' to 'AudioEffect*' in assignment
55:40: error: cannot convert 'std::shared_ptr<AudioEffect>' to 'AudioEffect*' in assignment
The code is as follows:
#include<stdlib.h>
#include<iostream>
#include<memory>`
//BASE CLASS
// audio and have a subsequent effect (next).
struct AudioEffect
{
virtual ~AudioEffect() = default;
virtual void process(float* buf, size_t num) = 0;
std::shared_ptr<AudioEffect> next;
};
//DERIVING MULTIPLE AUDIO-EFFECTS
//Noise Gate
struct NoiseGate: public AudioEffect
{
float threshold;
void process(float *buf, size_t num)
{
if (*buf > threshold)
*buf = threshold;
}
};
//Gain Boost
struct GainBoost: public AudioEffect
{
float signal;
void process(float *buf, size_t num)
{
*buf = *buf + signal;
}
};
//Compressor
struct Compressor: public AudioEffect
{
float offset;
void process(float *buf, size_t num)
{
*buf = *buf - offset;
}
};
//Function
// Implement a function that checks if there is a feedback loop
// in the effects chain.
//... detect_feedback(...)
//{
//}
bool detect_feedback (AudioEffect *ae)
{
AudioEffect *p, *q;
for (p = ae;p != NULL; p = p->next)
for (q = p->next; q != NULL; q = q->next)
if (typeid(*p) == typeid(*q))
return true;
return false;
}
//MAIN
int main(int argc, char *argv[])
{
return 0;
}
You can not assign a shared_ptr to a raw pointer. You need to use the .get() method to obtain a raw pointer.
(p->next).get()

No matching operands [template] / cannot convert from Type const* to Type

Let me post my code first:
Set.h
#pragma once
#include <string>
template<class _type> class Set
{
public:
Set();
Set m_add(Set _set1, Set _set2);
void m_addElem(Set *const _set, _type _elem);
void m_deleteElem(Set *const _set, _type _elem);
void m_addArray(_type _arr[], int _size);
Set(Set &_coll);
void operator+(_type _num);
void operator+(_type _elem[]);
Set operator+(Set *const _set);
void operator-(_type _num);
Set & operator=(Set &_set);
void m_display();
int m_check(_type elem);
~Set(void);
private:
_type * m_pelements;
int m_setSize;
};
Set.cpp
#pragma warning( disable : 4996 )
#include "Set.h"
#include <iostream>
#include <string>
template <class _type>
Set<_type>::Set()
{
m_setSize = 0;
}
template <class _type>
Set<_type>::Set(Set<_type> &_coll)
{
m_setSize = _coll.m_setSize;
m_pelements = new _type[_coll.m_setSize];
for (int i = 0;i<m_setSize;i++)
{
m_pelements[i] = _coll.m_pelements[i];
}
}
template <class _type>
Set<_type>::~Set()
{
delete [] m_pelements;
}
template <class _type>
Set<_type> Set<_type>::m_add(Set<_type> _set1, Set<_type> _set2)
{
Set<_type> finalSet;
finalSet = _set1;
for (int i = 0;i<_set2->m_setSize;i++)
{
m_addElem(finalSet, _set2->m_pelements[i]);
}
return finalSet;
}
template <class _type>
void Set<_type>::m_addElem(Set<_type> *const _set, _type _elem)
{
if (_set->m_setSize == 0)
{
_set->m_pelements = new _type[1];
_set->m_pelements[0] = _elem;
_set->m_setSize += 1;
}
else
{
_set->m_setSize += 1;
_type * helpElements = new _type[_set->m_setSize];
std::copy(_set->m_pelements, _set->m_pelements + _set->m_setSize-1, helpElements);
helpElements[_set->m_setSize-1] = _elem;
delete [] _set->m_pelements;
_set->m_pelements = helpElements;
/*
_type * helpElements = new _type[_set->m_setSize];
for (int i = 0;i<_set->m_setSize;i++)
{
helpElements[i] = _set->m_pelements[i];
}
delete _set->m_pelements;
_set->m_setSize += 1;
_set->m_pelements = new _type[_set->m_setSize];
for (int i = 0;i<_set->m_setSize;i++)
{
_set->m_pelements[i] = helpElements[i];
}
_set->m_pelements[_set->m_setSize-1] = _elem;
*/
}
}
template <class _type>
void Set<_type>::m_deleteElem(Set<_type> *const _set, _type _elem)
{
int index = _set->m_check(_elem);
if (index >= 0)
{
int k = 0;
_set->m_setSize -= 1;
_type * temp = new _type[_set->m_setSize];
for (int i = 0;i<_set->m_setSize;i++)
{
if (i == index)
k++;
temp[i] = _set->m_pelements[i+k];
}
delete [] _set->m_pelements;
_set->m_pelements = temp;
}
}
template <class _type>
void Set<_type>::m_addArray(_type _elem[], int size)
{
for (int i = 0;i<size;i++)
{
m_addElem(this,_elem[i]);
}
}
template <class _type>
void Set<_type>::operator+( _type _elem)
{
m_addElem(this,_elem);
}
template <class _type>
Set<_type> Set<_type>::operator+(Set<_type> *const _set)
{
return m_add(this,_set);
}
template <class _type>
void Set<_type>::operator+( _type _elem[])
{
m_addArray(this,_elem);
}
template <class _type>
void Set<_type>::operator-( _type _elem)
{
m_deleteElem(this,_elem);
}
template <class _type>
Set<_type> & Set<_type>::operator=(Set<_type> &_set)
{
if(&_set==this) return *this;
delete [] m_pelements;
m_setSize = _coll.m_setSize;
m_pelements = new _type[_coll.m_setSize];
for (int i = 0;i<m_setSize;i++)
{
m_pelements[i] = _coll.m_pelements[i];
}
}
template <class _type>
void Set<_type>::m_display()
{
for (int i = 0;i<m_setSize;i++)
{
std::cout << m_pelements[i] << " " ;
}
std::cout << std::endl;
}
template <class _type>
int Set<_type>::m_check(_type _elem)
{
for (int i = 0;i<m_setSize;i++)
{
if (m_pelements[i] == _elem)
return i;
}
return -1;
}
Main.cpp
#pragma warning( disable : 4996 )
#include "Set.h"
#include "Set.cpp"
#include <iostream>
int main()
{
Set<std::string> zbior1;
zbior1 + std::string("abc");
zbior1 + std::string("abcd");
zbior1 + std::string("abcdef");
zbior1 + std::string("XD");
zbior1.m_display();
zbior1 - "XD";
zbior1.m_display();
std::string tablica[3] = {"ala", "ma", "kota" };
zbior1.m_addArray(tablica,3);
zbior1.m_display();
Set<std::string> zbior2;
zbior2 + std::string("abDDc");
zbior2 + std::string("abcdDD");
zbior2 + std::string("abcdeDDf");
zbior2 + std::string("XDDD");
zbior2.m_display();
Set<std::string> zbior3;
zbior3 = zbior1 + zbior2; //HERE'S THE PROBLEM
}
Problem appears int the last line of Main.cpp
When arguments of Set operator+ are (Set *const _set) I get error " no operator found which takes a right-hand operand of type 'Set<_type>' (or there is no acceptable conversion)'" and if i remove *const there's different error saying "cannot convert parameter 1 from 'Set<_type> *const ' to 'Set<_type>'"
I have no idea how to repair it.
Your
Set operator+(Set *const _set);
is defined as taking a const pointer (which is for sure what you don't want), but you then pass to it an object instead, and not the address of an object. Pass by reference, like
Set operator+(Set const & _set);
Try reading Operator overloading for a very good introduction to the subject.
This method:
Set operator+(Set *const _set);
should probably look like:
Set operator+(Set const &rhs) const;
if it's going to stay a method. See the link in vsoftco's answer for why it should probably be a free non-friend function instead, implemented in terms of operator+=.
You pasted the same message for both errors, afaics, but at least one is complaining about the attempt to pass zbior2 to a method expecting a pointer.

Template, inheritance and operators

I have some trouble with class template inheritance and operators (operator +),
please have a look at these lines:
Base vector class (TVector.h):
template<class Real, int Size>
class TVector {
protected:
Real* values;
public:
...
virtual TVector<Real, Size>& operator=(const TVector<Real, Size>& rTVector) { //WORKS
int i = 0;
while (i<Size) {
*(values+i) = *(rTVector.values+i);
i++;
}
return *this;
}
virtual TVector<Real, Size> operator+(const TVector<Real, Size>& rTVector) const {
int i = 0;
Real* mem = (Real*)malloc(sizeof(Real)*Size);
memcpy(mem, values, Size);
while (i<Size) {
*(mem+i) += *(rTVector.values+i);
i++;
}
TVector<Real, Size> result = TVector<Real, Size>(mem);
free(mem);
return result;
}
};
2D vector class (TVector2.h):
template<class Real>
class TVector2: public TVector<Real, 2> {
public:
...
TVector2& operator=(const TVector2<Real>& rTVector) { //WORKS
return (TVector2&)(TVector<Real, 2>::operator=(rTVector));
}
TVector2 operator+(TVector2<Real>& rTVector) const { //ERROR
return (TVector2<Real>)(TVector<Real, 2>::operator+(rTVector));
}
};
Test (main.cpp):
int main(int argc, char** argv) {
TVector2<int> v = TVector2<int>();
v[0]=0;
v[1]=1;
TVector2<int> v1 = TVector2<int>();
v1.X() = 10;
v1.Y() = 15;
v = v + v1; //ERROR ON + OPERATOR
return 0;
}
Compilation error (VS2010):
Error 2 error C2440: 'cast de type' : cannot convert from
'TVector<Real,Size>' to 'TVector2' ...
What is wrong here ? is there a way to do this kind of stuff ?
Just looking for a way to not redefine all my Vectors classes.
I keep searching to do it, but I will be glad to get some help from you guys.
Sorry for bad English,
Best regards.
#include <memory>
using namespace std;
template<class Real, int Size> class TVector {
protected:
Real *_values;
public:
TVector() {
// allocate buffer
_values = new Real[Size];
}
TVector(Real *prValues) {
// check first
if (prValues == 0)
throw std::exception("prValues is null");
// allocate buffer
_values = new Real[Size];
// initialize buffer with values
for (unsigned int i(0U) ; i < Size ; ++i)
_values[i] = prValues[i];
}
// Do not forget copy ctor
TVector(TVector<Real, Size> const &rTVector) {
// allocate buffer
_values = new Real[Size];
// initialize with other vector
*this = rTVector;
}
virtual ~TVector() {
delete [] _values;
}
virtual Real &operator[](int iIndex) {
// check for requested index
if (iIndex < 0 || iIndex >= Size)
throw std::exception("requested index is out of bounds");
// index is correct. Return value
return *(_values+iIndex);
}
virtual TVector<Real, Size> &operator=(TVector<Real, Size> const &rTVector) {
// just copying values
for (unsigned int i(0U) ; i < Size ; ++i)
_values[i] = rTVector._values[i];
return *this;
}
virtual TVector<Real, Size> &operator+=(TVector<Real, Size> const &rTVector) {
for (unsigned int i(0U) ; i < Size ; ++i)
_values[i] += rTVector._values[i];
return *this;
}
virtual TVector<Real, Size> operator+(TVector<Real, Size> const &rTVector) {
TVector<Real, Size> tempVector(this->_values);
tempVector += rTVector;
return tempVector;
}
};
template<class Real> class TVector2: public TVector<Real, 2> {
public:
TVector2() {};
TVector2(Real *prValues): TVector(prValues) {}
TVector2 &operator=(TVector2<Real> const &rTVector) {
return static_cast<TVector2 &>(TVector<Real, 2>::operator=(rTVector));
}
TVector2 &operator+=(TVector2<Real> const &rTVector) {
return static_cast<TVector2 &>(TVector<Real, 2>::operator+=(rTVector));
}
TVector2 operator+(TVector2<Real> const &rTVector) {
return static_cast<TVector2 &>(TVector<Real, 2>::operator+(rTVector));
}
Real &X() { return _values[0]; }
Real &Y() { return _values[1]; }
};
int main(int argc, char** argv) {
TVector2<int> v = TVector2<int>();
v[0]=0;
v[1]=1;
TVector2<int> v1 = TVector2<int>();
v1.X() = 10;
v1.Y() = 15;
v = v1;
v += v1;
v = v + v1;
return 0;
}
Some misc notes:
it's very bad that you use malloc against of new. Real can be POD only to allow vector work well in your case. Use new or provide custom creation policy if you think that malloc provides better performance on PODs. Also do not forget to use delete [] instead of free while destroying memory buffer.
It's better to perform bounds checking while overloading operator[]
for better performance use ++i instead of postfix form. In former no temporary value is created.