C++ Code and Assembly traduction in Release

Do you know why C++ is the best ? Because it can be high level and very focus on optimized asm code generation. Here a sample of code:

 

#include "pch.h"

class Param
{
};

template<typename T>
class Factory
{
public:
static shared_ptr<T> CreateObject(const Param& param)
{
shared_ptr<T> pObj = nullptr;
pObj = make_shared<T>();

_pLastElement = pObj;
return pObj;
}

static shared_ptr<T> GetLastCreatedObject()
{
return _pLastElement;
}

private:
static shared_ptr<T> _pLastElement;
};

template<typename T>
shared_ptr<T> Factory<T>::_pLastElement = nullptr;

class Employee
{
};

class Product
{
};


template<typename T>
class Vector
{
public:
Vector(int size)
{
_size = size;
_data = new T[_size];
}

~Vector()
{
delete[] _data;
}

T GetData(int index)
{
return _data[index];
}

void SetData(int index, T value)
{
_data[index] = value;
}

private:
T* _data;
int _size = 0;
};

int main()
{
Vector<int> v1(10);
v1.SetData(2, 20);
int value = v1.GetData(2);
cout << value << endl; //20

Vector<string> v2(1000);
v2.SetData(10, "string 10");
v2.SetData(100, "string 100");
string value2 = v2.GetData(10);
cout << value2 << endl; // string 10

Vector<Product> v3(200000);

Param param;
shared_ptr<Employee> p1 = Factory<Employee>::CreateObject(param);
if (p1 != nullptr)
{
cout << "OK" << endl; //OK
}
shared_ptr<Employee> p2 = Factory<Employee>::CreateObject(param);
shared_ptr<Employee> p3 = Factory<Employee>::CreateObject(param);

shared_ptr<Employee> pLast = Factory<Employee>::GetLastCreatedObject();
if (pLast == p3)
{
cout << "OK ptr" << endl;
}
}

The result is an associated asm code generated : here

There is approximatively 1000 lines of asm for 100 lines of C++ with templates and shared_ptr. It’s amazing !

C++ rocks.

Advertisement

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: