• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



在下文中一共展示了unique_ptr类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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: process

void Stage::process(void)
{
  static ProcessingState last_processing_state = ProcessingState::Idle;
  static std::unique_ptr<StageBuilder> builder;
  bool done = false;

  // Have we changed states?
  if (impl->processing_state_ != last_processing_state)
  {
    // Clean up the last state if needed.
    switch (last_processing_state)
    {
    case ProcessingState::SmoothTerrain:
      impl->UpdateAllColumnData();
      break;

    default:
      break;
    }

    // Update the last processing state.
    last_processing_state = impl->processing_state_;

    // Initialize the new state if needed.
    switch (impl->processing_state_)
    {
    case ProcessingState::GenerateTerrain:
      builder.reset(
        new StageBuilderTerrain(*this, impl->seed_,
                                Settings::terrainStageHeight,
                                Settings::terrainFeatureHeight,
                                Settings::terrainFrequency,
                                Settings::terrainOctaveCount,
                                Settings::terrainPersistence,
                                Settings::terrainLacunarity));
      break;

    case ProcessingState::AddDeposits:
      builder.reset(new StageBuilderDeposits(*this, impl->seed_));
      break;

    case ProcessingState::AddLakes:
      builder.reset(
        new StageBuilderLakes(*this, impl->seed_,
                              Settings::terrainSeaLevel));
      break;

    case ProcessingState::AddBeaches:
      builder.reset(
        new StageBuilderBeaches(*this, impl->seed_,
                                Settings::terrainSeaLevel));
      break;

    case ProcessingState::AddRivers:
      builder.reset(
        new StageBuilderRivers(*this, impl->seed_,
                               Settings::terrainSeaLevel));
      break;

    case ProcessingState::AddFlora:
      builder.reset(
        new StageBuilderFlora(*this, impl->seed_,
                              Settings::terrainPlainsThreshold,
                              Settings::terrainForestThreshold));
      break;

    case ProcessingState::AddFauna:
      // TODO: create builder for this!
      builder.reset();
      break;

    case ProcessingState::SetPlayerKnowledge:
      builder.reset(new StageBuilderKnownStatus(*this, impl->seed_));
      break;

    default:
      builder.reset();
      break;
    }
  }

  if (builder.get() != nullptr)
  {
    done = builder->Build();
  }
  else
  {
    done = true;
  }

  // Other stuff to do while in the state.
  switch (impl->processing_state_)
  {
  case ProcessingState::Idle:
    // This is the state prior to world generation.
    break;

  case ProcessingState::GenerateTerrain:
    if (done)
    {
//.........这里部分代码省略.........
开发者ID:glindsey,项目名称:game-project-potential,代码行数:101,代码来源:Stage.cpp


示例7: Refresh

void CGUIEPGGridContainerModel::Refresh(const std::unique_ptr<CFileItemList> &items, const CDateTime &gridStart, const CDateTime &gridEnd, int iRulerUnit, int iBlocksPerPage, float fBlockSize)
{
  Reset();

  ////////////////////////////////////////////////////////////////////////
  // Create programme & channel items
  m_programmeItems.reserve(items->Size());
  CFileItemPtr fileItem;
  int iLastChannelID = -1;
  ItemsPtr itemsPointer;
  itemsPointer.start = 0;
  CPVRChannelPtr channel;
  int j = 0;
  for (int i = 0; i < items->Size(); ++i)
  {
    fileItem = items->Get(i);
    if (!fileItem->HasEPGInfoTag() || !fileItem->GetEPGInfoTag()->HasChannel())
      continue;

    m_programmeItems.emplace_back(fileItem);

    channel = fileItem->GetEPGInfoTag()->Channel();
    if (!channel)
      continue;

    int iCurrentChannelID = channel->ChannelID();
    if (iCurrentChannelID != iLastChannelID)
    {
      if (j > 0)
      {
        itemsPointer.stop = j - 1;
        m_epgItemsPtr.emplace_back(itemsPointer);
        itemsPointer.start = j;
      }
      iLastChannelID = iCurrentChannelID;
      m_channelItems.emplace_back(CFileItemPtr(new CFileItem(channel)));
    }
    ++j;
  }
  if (!m_programmeItems.empty())
  {
    itemsPointer.stop = m_programmeItems.size() - 1;
    m_epgItemsPtr.emplace_back(itemsPointer);
  }

  /* check for invalid start and end time */
  if (gridStart >= gridEnd)
  {
    // default to start "now minus GRID_START_PADDING minutes" and end "start plus one page".
    m_gridStart = CDateTime::GetUTCDateTime() - CDateTimeSpan(0, 0, GetGridStartPadding(), 0);
    m_gridEnd = m_gridStart + CDateTimeSpan(0, 0, iBlocksPerPage * MINSPERBLOCK, 0);
  }
  else if (gridStart > (CDateTime::GetUTCDateTime() - CDateTimeSpan(0, 0, GetGridStartPadding(), 0)))
  {
    // adjust to start "now minus GRID_START_PADDING minutes".
    m_gridStart = CDateTime::GetUTCDateTime() - CDateTimeSpan(0, 0, GetGridStartPadding(), 0);
    m_gridEnd = gridEnd;
  }
  else
  {
    m_gridStart = gridStart;
    m_gridEnd = gridEnd;
  }

  // roundup
  m_gridStart = CDateTime(m_gridStart.GetYear(), m_gridStart.GetMonth(), m_gridStart.GetDay(), m_gridStart.GetHour(), m_gridStart.GetMinute() >= 30 ? 30 : 0, 0);
  m_gridEnd = CDateTime(m_gridEnd.GetYear(), m_gridEnd.GetMonth(), m_gridEnd.GetDay(), m_gridEnd.GetHour(), m_gridEnd.GetMinute() >= 30 ? 30 : 0, 0);

  ////////////////////////////////////////////////////////////////////////
  // Create ruler items
  CDateTime ruler;
  ruler.SetFromUTCDateTime(m_gridStart);
  CDateTime rulerEnd;
  rulerEnd.SetFromUTCDateTime(m_gridEnd);
  CFileItemPtr rulerItem(new CFileItem(ruler.GetAsLocalizedDate(true)));
  rulerItem->SetProperty("DateLabel", true);
  m_rulerItems.emplace_back(rulerItem);

  const CDateTimeSpan unit(0, 0, iRulerUnit * MINSPERBLOCK, 0);
  for (; ruler < rulerEnd; ruler += unit)
  {
    rulerItem.reset(new CFileItem(ruler.GetAsLocalizedTime("", false)));
    rulerItem->SetLabel2(ruler.GetAsLocalizedDate(true));
    m_rulerItems.emplace_back(rulerItem);
  }

  FreeItemsMemory();

  ////////////////////////////////////////////////////////////////////////
  // Create epg grid
  const CDateTimeSpan blockDuration(0, 0, MINSPERBLOCK, 0);
  const CDateTimeSpan gridDuration(m_gridEnd - m_gridStart);
  m_blocks = (gridDuration.GetDays() * 24 * 60 + gridDuration.GetHours() * 60 + gridDuration.GetMinutes()) / MINSPERBLOCK;
  if (m_blocks >= MAXBLOCKS)
    m_blocks = MAXBLOCKS;
  else if (m_blocks < iBlocksPerPage)
    m_blocks = iBlocksPerPage;

  m_gridIndex.reserve(m_channelItems.size());
  const std::vector<GridItem> blocks(m_blocks);
//.........这里部分代码省略.........
开发者ID:Arcko,项目名称:xbmc,代码行数:101,代码来源:GUIEPGGridContainerModel.cpp


示例8: Get

Diagnostics* Diagnostics::Get()
{
    static std::unique_ptr<Diagnostics> singleton = make_unique<Diagnostics>();
    return singleton.get();
}
开发者ID:ViktorM,项目名称:raytracer,代码行数:5,代码来源:Diagnostics.cpp


示例9: appendChild

void Enum::appendChild(std::unique_ptr<ConstantAssignment> value)
{
	setAsParent(value.get());
	m_children.push_back(std::move(value));
}
开发者ID:tylerreisinger,项目名称:pidl,代码行数:5,代码来源:Enum.cpp


示例10: initializeFilter

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


示例11: 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


示例12: ISSnoopDevice

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


示例13: IsRealTimeStream

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


示例14: ISGetProperties

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


示例15: GetChannelsAmount

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


示例16: CloseLiveStream

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


示例17: DestroyDeviceObjects

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


示例18: 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


示例19: 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


示例20: transformImage

 DestinationImageType transformImage() override {
     return filter->apply(*this->sourceImage);
 }
开发者ID:jvff,项目名称:mestrado-implementacao,代码行数:3,代码来源:AbstractFilterTestData.hpp



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ std::unordered_map类代码示例发布时间:2022-05-31
下一篇:
C++ std::unique_lock类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap