Я создал класс для проверки некоторой функциональности, которую мне нужно использовать. По сути, класс возьмет глубокую копию переданной строки и сделает ее доступной через геттер. Я использую Visual Studio 2012. Unicode включен в настройках проекта.Глубокая копия массива TCHAR усечена
Проблема заключается в том, что операция memcpy дает усеченную строку. Результат такой же;
THISISATEST: InstanceDataConstructor: Testing testing 123
Testing te_READY
где первая линия является проверка прошла в TCHAR * строка & вторая линия является выходом из заполнения выделенной памяти с операцией тетсру. Ожидаемый результат; «Тестирование тестирования 123».
Может кто-нибудь объяснить, что здесь не так?
N.B. Получил #ifndef UNICODE определений типов отсюда: how-to-convert-tchar-array-to-stdstring
#ifndef INSTANCE_DATA_H//if not defined already
#define INSTANCE_DATA_H//then define it
#include <string>
//TCHAR is just a typedef, that depending on your compilation configuration, either defaults to char or wchar.
//Standard Template Library supports both ASCII (with std::string) and wide character sets (with std::wstring).
//All you need to do is to typedef String as either std::string or std::wstring depending on your compilation configuration.
//To maintain flexibility you can use the following code:
#ifndef UNICODE
typedef std::string String;
#else
typedef std::wstring String;
#endif
//Now you may use String in your code and let the compiler handle the nasty parts. String will now have constructors that lets you convert TCHAR to std::string or std::wstring.
class InstanceData
{
public:
InstanceData(TCHAR* strIn) : strMessage(strIn)//constructor
{
//Check to passed in string
String outMsg(L"THISISATEST: InstanceDataConstructor: ");//L for wide character string literal
outMsg += strMessage;//concatenate message
const wchar_t* finalMsg = outMsg.c_str();//prepare for outputting
OutputDebugStringW(finalMsg);//print the message
//Prepare TCHAR dynamic array. Deep copy.
charArrayPtr = new TCHAR[strMessage.size() +1];
charArrayPtr[strMessage.size()] = 0;//null terminate
std::memcpy(charArrayPtr, strMessage.data(), strMessage.size());//copy characters from array pointed to by the passed in TCHAR*.
OutputDebugStringW(charArrayPtr);//print the copied message to check
}
~InstanceData()//destructor
{
delete[] charArrayPtr;
}
//Getter
TCHAR* getMessage() const
{
return charArrayPtr;
}
private:
TCHAR* charArrayPtr;
String strMessage;//is used to conveniently ascertain the length of the passed in underlying TCHAR array.
};
#endif//header guard
используйте 'String' вместо' TCHAR * 'для' charArrayPtr' –
ваш 'memcpy' слишком короткий, третий аргумент shoudl - количество байтов, но вы передаете количество символов. Используйте 'std :: copy' isntead. –
Или, может быть, 'std :: memcpy (charArrayPtr, strMessage.data(), strMessage.size() * sizeof (TCHAR))' –