我想改进一些旧代码,因为它看起来很糟糕。我认为它的作用是可以完成的std::move
,对吗?整个代码发布在这个GitHub 上。但是,我只需要改进那个特定的结构(Resource
)。
用法是:
std::vector<Resource> ResourceHelper::resources;
bool ResourceHelper::EnumNamesFunc(HMODULE hModule, LPCWSTR lpType, LPWSTR lpName, LONG_PTR lParam)
{
if (!IS_INTRESOURCE(lpName))
{
std::wcout << lpName << std::endl;
}
else if (IS_INTRESOURCE(lpName))
{
std::cout << reinterpret_cast<int>(lpName) << std::endl;
}
HRSRC hResource = hResource = FindResourceW(hModule, lpName, lpType);
if (!hResource)
{
return false;
}
DWORD dwSize = SizeofResource(hModule, hResource);
HGLOBAL hGlobal = LoadResource(hModule, hResource);
if (!hGlobal)
{
return false;
}
LPVOID lpResource = LockResource(hGlobal);
if (!lpResource)
{
return false;
}
resources.push_back(Resource(lpType, lpName, hGlobal, dwSize));
FreeResource(lpResource);
return true;
}
片段
struct resource
{
LPCWSTR lpType;
LPWSTR lpName;
LPVOID lpData;
DWORD dwSize;
LPWSTR copy_string(LPCWSTR value)
{
if (IS_INTRESOURCE(value))
return const_cast<LPWSTR>(value);
int len = wcslen(value) + 1;
LPWSTR copy = new WCHAR[len];
memcpy(copy, value, sizeof(WCHAR) * len);
return copy;
}
resource(LPCWSTR lpType, const wchar_t* lpName, LPVOID lpData, DWORD dwSize)
{
this->lpType = copy_string(lpType);
this->lpName = copy_string(lpName);
this->lpData = lpData;
this->dwSize = dwSize;
}
resource(const resource& src)
{
this->lpType = copy_string(src.lpType);
this->lpName = copy_string(src.lpName);
this->lpData = src.lpData;
this->dwSize = src.dwSize;
}
~resource()
{
if (!IS_INTRESOURCE(lpType))
delete[] lpType;
if (!IS_INTRESOURCE(lpName))
delete[] lpName;
}
resource& operator=(const resource& rhs)
{
if (&rhs != this)
{
resource copy(rhs);
using std::swap;
swap(this->lpType, copy.lpType);
swap(this->lpName, copy.lpName);
swap(this->lpData, copy.lpData);
swap(this->dwSize, copy.dwSize);
}
return *this;
}
};
我的尝试
class resource
{
public:
resource() = default;
resource(const resource&) = delete;
resource(resource&& obj) noexcept
{
*this = std::move(obj);
}
~resource()
{
}
resource& operator=(const resource&) = delete;
resource& operator=(resource&& rhs) noexcept
{
std::swap(type, rhs.type);
std::swap(name, rhs.name);
std::swap(lpData, rhs.lpData);
std::swap(dwSize, rhs.dwSize);
return *this;
}
private:
LPCWSTR type;
LPWSTR name;
LPVOID lpData;
DWORD dwSize;
};