Sunday, February 7, 2016

C++ Safe Pointer coding model

There is a chance C++ can overtaken C# as high level language with better performance, full control and safety. Specifically, C++11/14 allocate memory through make_share and make_unique and end up tracking ownership to avoid dangling pointer.

#include "stdafx.h"
#include <memory>
#include <iostream>
#include <vector>

 auto sPtr = make_shared<int>(88);
 int* p = sPtr.get();

 sPtr = make_shared<int>(99); // Error: not allow to repoint.
 int* p1 = sPtr.get();
 *p1 = 33;
 cout << *p<< endl;

 const auto& locPtr = makeTempPtr(); //*makeTempPtr will not work must use local Ptr to save i.e. make_unique can not change owner due to ~
 int* p3 = locPtr.get();
 *p3 = 55;
 cout << *p3 << endl;


unique_ptr<int> makeTempPtr()
{
 return make_unique<int>();
}

Also vector<int> modification can be tracked by code analysis:

 auto sv = make_shared<vector<int>>(100);
 shared_ptr<vector<int>>* sv2 = &sv;
 vector<int>* pVec = &*sv;
 int* p2 = &(*sv)[0];

 // the promise is the following two lines should stopped by Code Analysis tool
 pVec->push_back(42);
 sv2->reset();

 (*pVec)[0] = 22;
 *p2 = 12;
 cout << (*pVec)[0] <<" "<< *p2<<endl;

No comments:

Post a Comment