【发布时间】:2018-09-05 07:06:26
【问题描述】:
考虑以下两个代码sn-ps, 第一个:
#include "pch.h"
#include <memory>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
class tcp_connection : public std::enable_shared_from_this<tcp_connection>
{
public:
typedef std::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_service& io_service)
{
return pointer(new tcp_connection(io_service));
//second example only differs by replacing the above line with the below one
//return std::make_shared<tcp_connection>(io_service);
}
private:
tcp_connection(boost::asio::io_service& io_service) //private constructor
: socket_(io_service)
{
}
tcp::socket socket_;
};
int main()
{
return 0;
}
第二个和第一个只有一行不同,即注释行。
使用 MSVC 2017 和 boost::asio 1.68,第一个版本按预期工作,而第二个版本无法编译,出现诸如“不允许 tcp_async 不完整类型”之类的错误。
我的问题是:
- 这是因为 std::make_shared 不能与 std:std::enable_shared_from_this 一起使用吗?
- 或者,这是因为 asio 关于如何实现 std::make_shared 或 std::enable_shared_from_this 的假设不适用于 MSVC 2017。
- 还是其他原因?
【问题讨论】:
-
请将示例编辑为minimal reproducible example。你不需要
boost::asio来演示问题,类定义是非法的。 -
std::make_shared与std::enable_shared_from_this配合得很好,这本身不应该是问题。 -
make_shared无法工作,因为您的构造函数是私有的,但无法重现您的不完整类型错误,请提供 minimal reproducible example
标签: c++ boost-asio shared-ptr