当前位置: 首页>>代码示例>>C++>>正文


C++ std::unique_ptr类代码示例

本文整理汇总了C++中std::unique_ptr的典型用法代码示例。如果您正苦于以下问题:C++ unique_ptr类的具体用法?C++ unique_ptr怎么用?C++ unique_ptr使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了unique_ptr类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: Sprite

	explicit Sprite(const std::unique_ptr<Texture> &texture) :
			Sprite(texture.get()) {
	}
开发者ID:SgtCoDFish,项目名称:APG,代码行数:3,代码来源:Sprite.hpp

示例2: CreateDeviceObjects

namespace OGL
{
// This are the initially requested size for the buffers expressed in bytes
const u32 MAX_IBUFFER_SIZE = 2 * 1024 * 1024;
const u32 MAX_VBUFFER_SIZE = 32 * 1024 * 1024;

static std::unique_ptr<StreamBuffer> s_vertexBuffer;
static std::unique_ptr<StreamBuffer> s_indexBuffer;
static size_t s_baseVertex;
static size_t s_index_offset;

VertexManager::VertexManager() : m_cpu_v_buffer(MAX_VBUFFER_SIZE), m_cpu_i_buffer(MAX_IBUFFER_SIZE)
{
  CreateDeviceObjects();
}

VertexManager::~VertexManager()
{
  DestroyDeviceObjects();
}

void VertexManager::CreateDeviceObjects()
{
  s_vertexBuffer = StreamBuffer::Create(GL_ARRAY_BUFFER, MAX_VBUFFER_SIZE);
  m_vertex_buffers = s_vertexBuffer->m_buffer;

  s_indexBuffer = StreamBuffer::Create(GL_ELEMENT_ARRAY_BUFFER, MAX_IBUFFER_SIZE);
  m_index_buffers = s_indexBuffer->m_buffer;

  m_last_vao = 0;
}

void VertexManager::DestroyDeviceObjects()
{
  s_vertexBuffer.reset();
  s_indexBuffer.reset();
}

void VertexManager::PrepareDrawBuffers(u32 stride)
{
  u32 vertex_data_size = IndexGenerator::GetNumVerts() * stride;
  u32 index_data_size = IndexGenerator::GetIndexLen() * sizeof(u16);

  s_vertexBuffer->Unmap(vertex_data_size);
  s_indexBuffer->Unmap(index_data_size);

  ADDSTAT(stats.thisFrame.bytesVertexStreamed, vertex_data_size);
  ADDSTAT(stats.thisFrame.bytesIndexStreamed, index_data_size);
}

void VertexManager::ResetBuffer(u32 stride)
{
  if (m_cull_all)
  {
    // This buffer isn't getting sent to the GPU. Just allocate it on the cpu.
    m_cur_buffer_pointer = m_base_buffer_pointer = m_cpu_v_buffer.data();
    m_end_buffer_pointer = m_base_buffer_pointer + m_cpu_v_buffer.size();

    IndexGenerator::Start((u16*)m_cpu_i_buffer.data());
  }
  else
  {
    auto buffer = s_vertexBuffer->Map(MAXVBUFFERSIZE, stride);
    m_cur_buffer_pointer = m_base_buffer_pointer = buffer.first;
    m_end_buffer_pointer = buffer.first + MAXVBUFFERSIZE;
    s_baseVertex = buffer.second / stride;

    buffer = s_indexBuffer->Map(MAXIBUFFERSIZE * sizeof(u16));
    IndexGenerator::Start((u16*)buffer.first);
    s_index_offset = buffer.second;
  }
}

void VertexManager::Draw(u32 stride)
{
  u32 index_size = IndexGenerator::GetIndexLen();
  u32 max_index = IndexGenerator::GetNumVerts();
  GLenum primitive_mode = 0;

  switch (m_current_primitive_type)
  {
  case PRIMITIVE_POINTS:
    primitive_mode = GL_POINTS;
    glDisable(GL_CULL_FACE);
    break;
  case PRIMITIVE_LINES:
    primitive_mode = GL_LINES;
    glDisable(GL_CULL_FACE);
    break;
  case PRIMITIVE_TRIANGLES:
    primitive_mode =
        g_ActiveConfig.backend_info.bSupportsPrimitiveRestart ? GL_TRIANGLE_STRIP : GL_TRIANGLES;
    break;
  }

  if (g_ogl_config.bSupportsGLBaseVertex)
  {
    glDrawRangeElementsBaseVertex(primitive_mode, 0, max_index, index_size, GL_UNSIGNED_SHORT,
                                  (u8*)nullptr + s_index_offset, (GLint)s_baseVertex);
  }
//.........这里部分代码省略.........
开发者ID:spxtr,项目名称:dolphin,代码行数:101,代码来源:VertexManager.cpp

示例3: downcast_unique

std::unique_ptr<T> downcast_unique(std::unique_ptr<U> p)
{
    return std::unique_ptr<T>(dynamic_cast<T*>(p.release()));
}
开发者ID:CCJY,项目名称:coliru,代码行数:4,代码来源:main.cpp

示例4: GetStickDirectionState

namespace HID {

// Handle to shared memory region designated to HID_User service
static Kernel::SharedPtr<Kernel::SharedMemory> shared_mem;

// Event handles
static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_1;
static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_2;
static Kernel::SharedPtr<Kernel::Event> event_accelerometer;
static Kernel::SharedPtr<Kernel::Event> event_gyroscope;
static Kernel::SharedPtr<Kernel::Event> event_debug_pad;

static u32 next_pad_index;
static u32 next_touch_index;
static u32 next_accelerometer_index;
static u32 next_gyroscope_index;

static int enable_accelerometer_count; // positive means enabled
static int enable_gyroscope_count;     // positive means enabled

static int pad_update_event;
static int accelerometer_update_event;
static int gyroscope_update_event;

// Updating period for each HID device. These empirical values are measured from a 11.2 3DS.
constexpr u64 pad_update_ticks = BASE_CLOCK_RATE_ARM11 / 234;
constexpr u64 accelerometer_update_ticks = BASE_CLOCK_RATE_ARM11 / 104;
constexpr u64 gyroscope_update_ticks = BASE_CLOCK_RATE_ARM11 / 101;

constexpr float accelerometer_coef = 512.0f; // measured from hw test result
constexpr float gyroscope_coef = 14.375f; // got from hwtest GetGyroscopeLowRawToDpsCoefficient call

static std::atomic<bool> is_device_reload_pending;
static std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeButton::NUM_BUTTONS_HID>
    buttons;
static std::unique_ptr<Input::AnalogDevice> circle_pad;
static std::unique_ptr<Input::MotionDevice> motion_device;
static std::unique_ptr<Input::TouchDevice> touch_device;

DirectionState GetStickDirectionState(s16 circle_pad_x, s16 circle_pad_y) {
    // 30 degree and 60 degree are angular thresholds for directions
    constexpr float TAN30 = 0.577350269f;
    constexpr float TAN60 = 1 / TAN30;
    // a circle pad radius greater than 40 will trigger circle pad direction
    constexpr int CIRCLE_PAD_THRESHOLD_SQUARE = 40 * 40;
    DirectionState state{false, false, false, false};

    if (circle_pad_x * circle_pad_x + circle_pad_y * circle_pad_y > CIRCLE_PAD_THRESHOLD_SQUARE) {
        float t = std::abs(static_cast<float>(circle_pad_y) / circle_pad_x);

        if (circle_pad_x != 0 && t < TAN60) {
            if (circle_pad_x > 0)
                state.right = true;
            else
                state.left = true;
        }

        if (circle_pad_x == 0 || t > TAN30) {
            if (circle_pad_y > 0)
                state.up = true;
            else
                state.down = true;
        }
    }

    return state;
}

static void LoadInputDevices() {
    std::transform(Settings::values.buttons.begin() + Settings::NativeButton::BUTTON_HID_BEGIN,
                   Settings::values.buttons.begin() + Settings::NativeButton::BUTTON_HID_END,
                   buttons.begin(), Input::CreateDevice<Input::ButtonDevice>);
    circle_pad = Input::CreateDevice<Input::AnalogDevice>(
        Settings::values.analogs[Settings::NativeAnalog::CirclePad]);
    motion_device = Input::CreateDevice<Input::MotionDevice>(Settings::values.motion_device);
    touch_device = Input::CreateDevice<Input::TouchDevice>(Settings::values.touch_device);
}

static void UnloadInputDevices() {
    for (auto& button : buttons) {
        button.reset();
    }
    circle_pad.reset();
    motion_device.reset();
    touch_device.reset();
}

static void UpdatePadCallback(u64 userdata, int cycles_late) {
    SharedMem* mem = reinterpret_cast<SharedMem*>(shared_mem->GetPointer());

    if (is_device_reload_pending.exchange(false))
        LoadInputDevices();

    PadState state;
    using namespace Settings::NativeButton;
    state.a.Assign(buttons[A - BUTTON_HID_BEGIN]->GetStatus());
    state.b.Assign(buttons[B - BUTTON_HID_BEGIN]->GetStatus());
    state.x.Assign(buttons[X - BUTTON_HID_BEGIN]->GetStatus());
    state.y.Assign(buttons[Y - BUTTON_HID_BEGIN]->GetStatus());
    state.right.Assign(buttons[Right - BUTTON_HID_BEGIN]->GetStatus());
//.........这里部分代码省略.........
开发者ID:JayFoxRox,项目名称:citra,代码行数:101,代码来源:hid.cpp

示例5: refreshActiveMetadata

void MetadataManager::refreshActiveMetadata(std::unique_ptr<CollectionMetadata> remoteMetadata) {
    LOG(1) << "Refreshing the active metadata from "
           << (_activeMetadataTracker->metadata ? _activeMetadataTracker->metadata->toStringBasic()
                                                : "(empty)")
           << ", to " << (remoteMetadata ? remoteMetadata->toStringBasic() : "(empty)");

    stdx::lock_guard<stdx::mutex> scopedLock(_managerLock);

    // Collection is not sharded anymore
    if (!remoteMetadata) {
        log() << "Marking collection as not sharded.";

        _receivingChunks.clear();
        _rangesToClean.clear();

        _setActiveMetadata_inlock(nullptr);
        return;
    }

    invariant(!remoteMetadata->getCollVersion().isWriteCompatibleWith(ChunkVersion::UNSHARDED()));
    invariant(!remoteMetadata->getShardVersion().isWriteCompatibleWith(ChunkVersion::UNSHARDED()));

    // Collection is not sharded currently
    if (!_activeMetadataTracker->metadata) {
        log() << "Marking collection as sharded with " << remoteMetadata->toStringBasic();

        invariant(_receivingChunks.empty());
        invariant(_rangesToClean.empty());

        _setActiveMetadata_inlock(std::move(remoteMetadata));
        return;
    }

    // If the metadata being installed has a different epoch from ours, this means the collection
    // was dropped and recreated, so we must entirely reset the metadata state
    if (_activeMetadataTracker->metadata->getCollVersion().epoch() !=
        remoteMetadata->getCollVersion().epoch()) {
        log() << "Overwriting collection metadata due to epoch change.";

        _receivingChunks.clear();
        _rangesToClean.clear();

        _setActiveMetadata_inlock(std::move(remoteMetadata));
        return;
    }

    // We already have newer version
    if (_activeMetadataTracker->metadata->getCollVersion() >= remoteMetadata->getCollVersion()) {
        LOG(1) << "Attempted to refresh active metadata "
               << _activeMetadataTracker->metadata->toStringBasic() << " with an older "
               << remoteMetadata->toStringBasic();

        return;
    }

    // Resolve any receiving chunks, which might have completed by now
    for (auto it = _receivingChunks.begin(); it != _receivingChunks.end();) {
        const BSONObj min = it->first;
        const BSONObj max = it->second;

        // Our pending range overlaps at least one chunk
        if (rangeMapContains(remoteMetadata->getChunks(), min, max)) {
            // The remote metadata contains a chunk we were earlier in the process of receiving, so
            // we deem it successfully received.
            LOG(2) << "Verified chunk " << ChunkRange(min, max).toString()
                   << " was migrated earlier to this shard";

            _receivingChunks.erase(it++);
            continue;
        } else if (!rangeMapOverlaps(remoteMetadata->getChunks(), min, max)) {
            ++it;
            continue;
        }

        // Partial overlap indicates that the earlier migration has failed, but the chunk being
        // migrated underwent some splits and other migrations and ended up here again. In this
        // case, we will request full reload of the metadata. Currently this cannot happen, because
        // all migrations are with the explicit knowledge of the recipient shard. However, we leave
        // the option open so that chunk splits can do empty chunk move without having to notify the
        // recipient.
        RangeVector overlappedChunks;
        getRangeMapOverlap(remoteMetadata->getChunks(), min, max, &overlappedChunks);

        for (const auto& overlapChunkMin : overlappedChunks) {
            auto itRecv = _receivingChunks.find(overlapChunkMin.first);
            invariant(itRecv != _receivingChunks.end());

            const ChunkRange receivingRange(itRecv->first, itRecv->second);

            _receivingChunks.erase(itRecv);

            // Make sure any potentially partially copied chunks are scheduled to be cleaned up
            _addRangeToClean_inlock(receivingRange);
        }

        // Need to reset the iterator
        it = _receivingChunks.begin();
    }

    // For compatibility with the current range deleter, which is driven entirely by the contents of
//.........这里部分代码省略.........
开发者ID:ChineseDr,项目名称:mongo,代码行数:101,代码来源:metadata_manager.cpp

示例6: initializeFilter

 void initializeFilter(ParameterTypes... parameters) {
     filter.reset(new FilterType(parameters...));
 }
开发者ID:jvff,项目名称:mestrado-implementacao,代码行数:3,代码来源:AbstractFilterTestData.hpp

示例7: ISNewText

void ISNewText(	const char *dev, const char *name, char *texts[], char *names[], int num)
{
        scope->ISNewText(dev, name, texts, names, num);
}
开发者ID:mp77,项目名称:indi,代码行数:4,代码来源:ieqpro.cpp

示例8: ISSnoopDevice

void ISSnoopDevice (XMLEle *root)
{
   scope->ISSnoopDevice(root);
}
开发者ID:mp77,项目名称:indi,代码行数:4,代码来源:ieqpro.cpp

示例9: IsRealTimeStream

bool IsRealTimeStream(void)
{
  return !g_pvr_client->is_timeshifting();
}
开发者ID:wozio,项目名称:pvr.home-system,代码行数:4,代码来源:client.cpp

示例10: ISGetProperties

void ISGetProperties(const char *dev)
{
        scope->ISGetProperties(dev);
}
开发者ID:mp77,项目名称:indi,代码行数:4,代码来源:ieqpro.cpp

示例11: GetChannelsAmount

int GetChannelsAmount(void)
{
  return g_pvr_client->get_channels_num();
}
开发者ID:wozio,项目名称:pvr.home-system,代码行数:4,代码来源:client.cpp

示例12: CloseLiveStream

void CloseLiveStream(void)
{
  if (XBMC)
    XBMC->Log(LOG_DEBUG, "CloseLiveStream");
  g_pvr_client->destroy_session();
}
开发者ID:wozio,项目名称:pvr.home-system,代码行数:6,代码来源:client.cpp

示例13: DestroyDeviceObjects

void VertexManager::DestroyDeviceObjects()
{
  s_vertexBuffer.reset();
  s_indexBuffer.reset();
}
开发者ID:spxtr,项目名称:dolphin,代码行数:5,代码来源:VertexManager.cpp

示例14: sendRequests

void Controller::sendRequests() {
    // Connector::connect()

    try {
        connector_ptr_->connect(num_connect_attempts_);
    } catch (PCPClient::connection_config_error& e) {
        std::string err_msg { "failed to configure WebSocket: " };
        throw controller_error { err_msg + e.what() };
    } catch (PCPClient::connection_fatal_error& e) {
        std::string err_msg { "failed to connect to " + BROKER_URL + " or "
                              + FAILOVER_URL + " after "
                              + std::to_string(num_connect_attempts_)
                              + " attempts: " };
        throw controller_error { err_msg + e.what() };
    }

    // Connector::isConnected()

    if (connector_ptr_->isConnected()) {
        std::cout << "Successfully connected\n";
    } else {
        // The connection has dropped; we can't send anything
        throw controller_error { "connection dropped" };
    }

    // Send a valid request - a response is expected

    leatherman::json_container::JsonContainer track {
        "{\"artist\" : \"Captain Beefheart\"}" };
    leatherman::json_container::JsonContainer valid_request {};
    valid_request.set<leatherman::json_container::JsonContainer>("request", track);
    valid_request.set<std::string>("details", "please send some good music");

    std::vector<std::string> endpoints { "pcp://*/" + AGENT_CLIENT_TYPE };

    try {
        auto id = connector_ptr_->send(endpoints,
                                       REQUEST_SCHEMA_NAME,
                                       MSG_TIMEOUT_S,
                                       valid_request);
        std::cout << "Valid request message sent; message id: " << id << "\n";
    } catch (PCPClient::connection_processing_error& e) {
        std::string err_msg { "failed to send the request message: " };
        throw controller_error { err_msg + e.what() };
    }

    // Send an invalid request - an error message should arrive

    leatherman::json_container::JsonContainer bad_json {
        "{\"genre\" : \"experimental rock\"}" };
    leatherman::json_container::JsonContainer bad_request {};
    bad_request.set<leatherman::json_container::JsonContainer>("request", bad_json);
    bad_request.set<std::string>("details", "I'm not sure about this");

    try {
        auto id = connector_ptr_->send(endpoints,
                                       REQUEST_SCHEMA_NAME,
                                       MSG_TIMEOUT_S,
                                       bad_request);
        std::cout << "Bad request message sent; message id: " << id << "\n";
    } catch (PCPClient::connection_processing_error& e) {
        std::string err_msg { "failed to send the request message: " };
        throw controller_error { err_msg + e.what() };
    }

    // Send an inventory request to the broker

    leatherman::json_container::JsonContainer inventory_request {};
    std::vector<std::string> query { "cth://*/" + AGENT_CLIENT_TYPE };
    inventory_request.set<std::vector<std::string>>("query", query);

    try {
        // NB: use "cth:///server" with 3 '/' as the broker URI
        auto id  = connector_ptr_->send(std::vector<std::string> { "cth:///server" },
                                        PCPClient::Protocol::INVENTORY_REQ_TYPE,
                                        MSG_TIMEOUT_S,
                                        inventory_request);
        std::cout << "Inventory request message sent; message id: " << id << "\n";
    } catch (PCPClient::connection_processing_error& e) {
        std::string err_msg { "failed to send the inventory request message: " };
        throw controller_error { err_msg + e.what() };
    }

    // Wait for the response and error messages
    sleep(2);
}
开发者ID:MikaelSmith,项目名称:cpp-pcp-client,代码行数:86,代码来源:main.cpp

示例15: SendSinglePacketHelper

ssize_t UdpTransport::SendSinglePacketHelper(
        Header* header, const uint8_t* tx_data, size_t tx_length, uint8_t* rx_data,
        size_t rx_length, const int attempts, std::string* error) {
    ssize_t total_data_bytes = 0;
    error->clear();

    int attempts_left = attempts;
    while (attempts_left > 0) {
        if (!socket_->Send({{header->bytes(), kHeaderSize}, {tx_data, tx_length}})) {
            *error = Socket::GetErrorMessage();
            return -1;
        }

        // Keep receiving until we get a matching response or we timeout.
        ssize_t bytes = 0;
        do {
            bytes = socket_->Receive(rx_packet_.data(), rx_packet_.size(), kResponseTimeoutMs);
            if (bytes == -1) {
                if (socket_->ReceiveTimedOut()) {
                    break;
                }
                *error = Socket::GetErrorMessage();
                return -1;
            } else if (bytes < static_cast<ssize_t>(kHeaderSize)) {
                *error = "protocol error: incomplete header";
                return -1;
            }
        } while (!header->Matches(rx_packet_.data()));

        if (socket_->ReceiveTimedOut()) {
            --attempts_left;
            continue;
        }
        ++sequence_;

        // Save to |error| or |rx_data| as appropriate.
        if (rx_packet_[kIndexId] == kIdError) {
            error->append(rx_packet_.data() + kHeaderSize, rx_packet_.data() + bytes);
        } else {
            total_data_bytes += bytes - kHeaderSize;
            size_t rx_data_bytes = std::min<size_t>(bytes - kHeaderSize, rx_length);
            if (rx_data_bytes > 0) {
                memcpy(rx_data, rx_packet_.data() + kHeaderSize, rx_data_bytes);
                rx_data += rx_data_bytes;
                rx_length -= rx_data_bytes;
            }
        }

        // If the response has a continuation flag we need to prompt for more data by sending
        // an empty packet.
        if (rx_packet_[kIndexFlags] & kFlagContinuation) {
            // We got a valid response so reset our attempt counter.
            attempts_left = attempts;
            header->Set(rx_packet_[kIndexId], sequence_, kFlagNone);
            tx_data = nullptr;
            tx_length = 0;
            continue;
        }

        break;
    }

    if (attempts_left <= 0) {
        *error = "no response from target";
        return -1;
    }

    if (rx_packet_[kIndexId] == kIdError) {
        *error = "target reported error: " + *error;
        return -1;
    }

    return total_data_bytes;
}
开发者ID:ArtBears,项目名称:platform_system_core,代码行数:74,代码来源:udp.cpp


注:本文中的std::unique_ptr类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。