c++ - 如何使用 shared_ptr 确保指针存在?

标签 c++ c++11 boost-asio shared-ptr

我正在尝试使用 Boost::asio 运行一个程序.这是我用来执行 async_write() 的方法:

template<typename T>
void Write(shared_ptr<std::vector<T>> data){
    std::cout << "Write Method [std::vector]" << std::endl;

    ioService.post(boost::bind(&TCPClient::DoWrite<T>, this, data));
}

然后,DoWrite()调用方法实际发送 vector 中的数据:

template<typename T>
void DoWrite(shared_ptr<std::vector<T>> data){
std::cout << "DoWrite Method [std::vector]" << std::endl;

boost::asio::async_write(   socket_,
                            boost::asio::buffer(*data),
                            boost::bind(&TCPClient::handle_write,
                            this, boost::asio::placeholders::error,
                            boost::asio::placeholders::bytes_transferred)
                        );
std::cout << "async_write executed" << std::endl;

但是在运行时我得到这个错误:

Program: C:\Windows\SYSTEM32\MSVCP120D.dll File: C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\vector Line: 72

Expression: vector iterator not dereferencable

经过调查我知道问题是 std::vector<T>传递给该方法的时间不够长,当写入发生时(因为它是异步的) vector 不存在,所以我收到此错误。

我知道问题是因为如果我删除 template我的功能现在是这样的:

void DoWrite(std::vector<char> data){
    std::cout << "DoWrite Method [std::vector]" << std::endl;

    backupVector = data;

    boost::asio::async_write(   socket_,
                                boost::asio::buffer(backupVector),
                                boost::bind(&TCPClient::handle_write,
                                this, boost::asio::placeholders::error,
                                boost::asio::placeholders::bytes_transferred)
                            );
    std::cout << "async_write executed" << std::endl;
}

在哪里backupVectorstd::vector<char>在类中我没有收到错误,因为我有一个存在的引用,但我无法在运行时创建一个 std::vector<T>将传入的 vector 存储在类中(我说得对吗?我是 C++ 的新手)。 所以我读到了 shared_ptr :

std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer. Several shared_ptr objects may own the same object. The object is destroyed and its memory deallocated when either of the following happens:

  • The last remaining shared_ptr owning the object is destroyed.

  • The last remaining shared_ptr owning the object is assigned another pointer via operator= or reset().

所以如果我将指针传递给 async_write如果一个对象引用了它,为什么它会被“销毁”?还有其他方法吗?

这就是我使用 Write() 的方式方法:

std::vector<char> data;
data.push_back('B');
data.push_back(bValue);

client.Write<char>(make_shared<std::vector<char>>(data));

Sleep(100000);

最佳答案

我远不能说出你应该在这里做什么(缺少信息并且只使用了几次 asio),但是从 this example 猜测,您应该能够使用类似于以下内容的自定义缓冲区类来传递缓冲区:

// based on http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/example/cpp11/buffers/reference_counted.cpp
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

template<class T>
class shared_const_buffer
{
public:
  // Construct from a `shared_ptr`
  explicit shared_const_buffer(std::shared_ptr<std::vector<T>> const& p_data)
    : data_(p_data),
      buffer_(boost::asio::buffer(*data_))
  {}

  // Implement the ConstBufferSequence requirements.
  using value_type = boost::asio::const_buffer;
  using const_iterator = boost::asio::const_buffer const*;

  boost::asio::const_buffer const* begin() const { return &buffer_; }
  boost::asio::const_buffer const* end() const { return &buffer_ + 1; }

private:
  std::shared_ptr<std::vector<T>> data_;
  boost::asio::const_buffer buffer_;
};

正如我在对该问题的评论中提到的,我不知道不知道为发送(写入)传递共享缓冲区是否是个好主意。


这是如何工作的:

在写函数中,你传入一个缓冲区:

boost::asio::async_write(   socket_,
                            boost::asio::buffer(backupVector), /*...*/ );

在此示例中,缓冲区是通过 boost::asio::buffer 函数创建的。但是这个函数不获取(也不共享)参数的所有权,它只存储一个引用/指针。传递的缓冲区对象被复制到套接字中(在作业队列中),它一直存在到作业完成为止。

通过使用 shared_const_buffer 而不是 boost::asio::buffer 创建的缓冲区对象,我们将 vector 的生命周期至少延长到创建的 vector 的生命周期shared_const_buffer 对象。因此, vector 至少在作业完成之前一直存在。

参见 the documentation of async_writethe documentation of the buffer function / buffer invalidation .

关于c++ - 如何使用 shared_ptr 确保指针存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20818297/

相关文章:

c++ - Qt Creator 编译错误(找不到.o 文件)

c++ - 在 GYP 项目中使用 c++11

c++ - Visual Studio 无法在 bool 运算的上下文中实例化强制转换(转换)运算符模板 (T=bool)

boost - 使用 boost::asio::io_service::post()

c++ - Boost.Asio 错误的本地端点

c++ - 我向 HTTP 服务器发送 TCP 请求 - 但没有任何响应

c++ - 重新分配(): invalid old size even when malloc() is used to allocate memory

c++ - 为什么不为 std::tuple 重载 STL 算法?

c++ - 棘手的空检查和调用

c++ - 使用 "redefinition"关键字时 "differs in levels of indirection"错误更改为 `auto`