[a / b / c / d / e / f / g / gif / h / hr / k / m / o / p / r / s / t / u / v / vg / vm / vmg / vr / vrpg / vst / w / wg] [i / ic] [r9k / s4s / vip / qa] [cm / hm / lgbt / y] [3 / aco / adv / an / bant / biz / cgl / ck / co / diy / fa / fit / gd / hc / his / int / jp / lit / mlp / mu / n / news / out / po / pol / pw / qst / sci / soc / sp / tg / toy / trv / tv / vp / vt / wsg / wsr / x / xs] [Settings] [Search] [Mobile] [Home]
Board
Settings Mobile Home
/g/ - Technology


Thread archived.
You cannot reply anymore.


[Advertise on 4chan]


File: 1439087324918.jpg (18 KB, 400x386)
18 KB
18 KB JPG
>mfw trying to learn RAII

#include <iostream>

template<typename T>
class Auto_ptr5
{
T* m_ptr {};
public:
Auto_ptr5(T* ptr = nullptr)
: m_ptr { ptr }
{
}

~Auto_ptr5()
{
delete m_ptr;
}

// Copy constructor -- no copying allowed!
Auto_ptr5(const Auto_ptr5& a) = delete;

// Move constructor
// Transfer ownership of a.m_ptr to m_ptr
Auto_ptr5(Auto_ptr5&& a) noexcept
: m_ptr(a.m_ptr)
{
a.m_ptr = nullptr;
}

// Copy assignment -- no copying allowed!
Auto_ptr5& operator=(const Auto_ptr5& a) = delete;

// Transfer ownership of a.m_ptr to m_ptr
Auto_ptr5& operator=(Auto_ptr5&& a) noexcept
{
// Self-assignment detection
if (&a == this)
return *this;

// Release any resource we're holding
delete m_ptr;

// Transfer ownership of a.m_ptr to m_ptr
m_ptr = a.m_ptr;
a.m_ptr = nullptr;

return *this;
}

T& operator*() const { return *m_ptr; }
T* operator->() const { return m_ptr; }
bool isNull() const { return m_ptr == nullptr; }
};
>>
File: 1436713903927.jpg (25 KB, 250x241)
25 KB
25 KB JPG
>m_ptr
>Auto_ptr5
>>
>>101563599
It seems you are trying to implement unique_ptr, i'll give you some tips:
Always theck if this->m_ptr is not null before calling delete
For your assignment operators, you can use friend to explicitly qualify what kind of operations are allowed i.e
// Moves self into other
friend Auto_ptr5& operator=(Auto_ptr5& self, Auto_ptr5&& other)
{
if (self.m_ptr) delete self.m_ptr;

self.m_ptr = other.m_ptr;
other.m_ptr = nullptr

return self;
}

You can also use the deducing this feature, but I don't think it's very stable right now

Also you should provide a way to automatically create your auto_ptr i.e
template <class U, class... Ts>
decltype(auto) make_autoptr5(Ts&&... ts)
{
return Auto_ptr5(new U(std::forward<Ts>(ts)...));
}

If i were you, i'd disable the possibility to create an Auto_ptr from a raw pointer or throw an exception if it is null because your dereference method might crash your program when least expect it



[Advertise on 4chan]

Delete Post: [File Only] Style:
[Disable Mobile View / Use Desktop Site]

[Enable Mobile View / Use Mobile Site]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.