简体   繁体   English

无法使用 `std::make_shared` 分配指针

[英]Cannot allocate a pointer using `std::make_shared`

I have some trouble understanding what is the difference in terms of creating a new object of an abstract class using std::make_shared and std::shared_ptr ?我很难理解使用std::make_sharedstd::shared_ptr创建抽象 class 的new object 有什么区别? So in my specific case, I am not able to use this:所以在我的具体情况下,我无法使用它:

p_network_connection_ = std::make_shared<awsiotsdk::NetworkConnection> (awsiotsdk::ConfigCommon::endpoint_);

But able to do this:但能够做到这一点:

p_network_connection_ = std::shared_ptr<awsiotsdk::NetworkConnection>(new awsiotsdk::network::WebSocketConnection(awsiotsdk::ConfigCommon::endpoint_);

How come?怎么来的? As if I try the first method (using std::make_shared ), I get this error:好像我尝试第一种方法(使用std::make_shared ),我收到此错误:

 error: invalid new-expression of abstract class type ‘awsiotsdk::NetworkConnection’
  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

Uhm it looks like you are creating instances of different classes.嗯,看起来您正在创建不同类的实例。 In your first example, you attempt to create an instance of awsiotsdk::NetworkConnection class.在您的第一个示例中,您尝试创建awsiotsdk::NetworkConnection class 的实例。 Given the error, I can assume that it is an abstract class - and thus an instance of this can not be created.鉴于错误,我可以假设它是一个抽象的 class - 因此无法创建此实例。 In your second example you are creating an instance of new awsiotsdk::network::WebSocketConnection class.在第二个示例中,您正在创建new awsiotsdk::network::WebSocketConnection class 的实例。 Given that it 'works' for you - it is not an abstruct class:)鉴于它对您“有效”-它不是抽象的 class :)

So why not to try:那么为什么不尝试:

p_network_connection_ = std::make_shared<awsiotsdk::network::WebSocketConnection> (awsiotsdk::ConfigCommon::endpoint_);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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