简体   繁体   中英

Memcpy C++ alternative

I am using the library SDL2 on Windows 10 with the MSVC (aka. Visual C++) compiler for a personal project. I am having troubles while trying to handle input. The code is as follows and it's origin is from here :

// InputManager.hpp

#include <SDL2/SDL.h>

class InputManager
{
public:
    static InputManager *This();
    // ... 

private:
    InputManager(); // this is a singleton class.

    const Uint8* currentkb;
    Uint8* prevkb;
    int keyLength;
    // ...
};
// InpuManager.cpp

InputManager* InputManager::This()
{
    static InputManager ret;
    return ret;
}

InputManager::InputManager()
{
    currentkb = SDL_GetKeyboardState(&keyLength);
    prevkb = new Uint8[keyLength];
    memcpy(prevkb, currentkb, keylength);
}

// ...

I want to do the copying of the data from currentkb to prevkb without using memcpy, and possibly , use a more "C++ friendly" (that works in C++ but not in C) and safe way.

Since pointers are RandomAccessIterator and you have the number of available consecutive elements, you can use the InputIterator ctor ofstd::vector<T> :

const auto * const currentkb = SDL_GetKeyboardState(&keyLength);
std::vector<std::uint8_t> prevkb(currentkb, currentkb + keyLength);

For existing variables you can also usestd::vector<T>::assign :

prevkb.assign(currentkb, currentkb + keyLength);

Or use move assignment: (It probably won't make a difference in the end)

prevkb = decltype(prevkb)(currentkb, currentkb + keyLength);

Perhaps the simplest change is to use std::copy or std::copy_n instead of memcpy . They're type-safe and with trivially copyable data types they will probably compile to a memcpy or memmove call and get the speed benefit of those highly-optimized functions.

std::copy(currentkb, currentkb + keylength, prevkb);

or

std::copy_n(currentkb, keylength, prevkb);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM