aboutsummaryrefslogtreecommitdiff
path: root/c/wcharptr.cpp
blob: f36c6207c032591585344ffa0accbf1dfb94826b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <utility>
#include <windows.h>

#include "wcharptr.h"
#include "win.h"

WcharPtr WcharPtr::FromNarrow(const char* const src, const int cp)
{
	int cchNarrow = strlen(src)+1;
	int cchWide = MultiByteToWideChar(cp, 0, src, cchNarrow, nullptr, 0);
	wchar_t* dst = new wchar_t[cchWide];
	if (!MultiByteToWideChar(cp, 0, src, cchNarrow, dst, cchWide)) {
		delete dst;
		throw Win32Error();
	}
	return dst;
}

WcharPtr WcharPtr::Copy(const wchar_t* const src)
{
	const int cch = wcslen(src)+1;
	wchar_t* dst = new wchar_t[cch];
	memcpy(dst, src, cch*sizeof(wchar_t));
	return dst;
}


WcharPtr::WcharPtr() noexcept {}

WcharPtr::~WcharPtr() noexcept
{
	delete m_p;
}

WcharPtr::operator wchar_t*() noexcept
{
	return m_p;
}

WcharPtr::WcharPtr(wchar_t* const s) noexcept : m_p(s) {}

WcharPtr& WcharPtr::operator=(wchar_t* const s) noexcept
{
	if (m_p != s) {
		delete m_p;
		m_p = s;
	}
	return *this;
}

WcharPtr::WcharPtr(WcharPtr&& other) noexcept
	: m_p(std::exchange(other.m_p, nullptr)) {}

WcharPtr& WcharPtr::operator=(WcharPtr&& other) noexcept
{
	std::swap(m_p, other.m_p);
	return *this;
}

wchar_t* WcharPtr::Release() noexcept
{
	wchar_t* p2 = m_p;
	m_p = nullptr;
	return p2;
}