【问题标题】:no match for ‘operator=’ when std::shared_ptr当 std::shared_ptr 不匹配‘operator=’
【发布时间】:2021-03-12 06:51:21
【问题描述】:

我看到一个代码正是使用这个,但是那个代码可以工作而我的不行,知道为什么吗?

PD:我正在尝试实现这个commit。看看代码是不是一模一样

for(const auto& tx : block.vtx)
    if (txHash == tx->GetHash()) {
        txNew = tx;
        foundAtOut = *pindex;
        return true;
    }
main.cpp:2471:25: error: no match for ‘operator=’ (operand types are ‘CTransactionRef’ {aka ‘std::shared_ptr<const CTransaction>’} and ‘const CTransaction’)
             txNew = tx;

【问题讨论】:

  • shared_ptr::operator= 期望分配一个原始指针、另一个 shared_ptrunique_ptrtxNewshared_ptr,但 txshared_ptr 不兼容。

标签: c++ shared-ptr


【解决方案1】:

仔细阅读错误信息:您正在尝试将const CTransaction 类型的对象分配给std::shared_ptr&lt;const CTransaction&gt; 类型的共享指针。但是您不能使用operator= 来做到这一点,因为它的参数应该是shared_ptrunique_ptr,如cppreference 所述。

我认为,根据您的实际代码,您可以为const CTransaction 对象创建一个新的shared_ptr,然后分配给它。

【讨论】:

  • @ValentinoZaffrani 从错误消息中可以明显看出这一点。不明显的是 block.vtx 是什么,以及为什么您希望它的元素与 CTransactionRef 的赋值兼容
  • @ValentinoZaffrani tx 不是const CTransaction*,而是const CTransaction - 如果tx 是一个指针,你需要txNew.reset(tx)
  • @ValentinoZaffrani 使用&amp; 使tx 成为引用,而不是指针。这意味着block.vtx 必须是CTransaction 对象,而不是CTransaction* 指针,才能绑定引用。
  • @ValentinoZaffrani 如果您创建minimal reproducible example,有人会告诉您为什么它不起作用。某些外部 repo 中的提交不是 minimal reproducible example - 并且该提交可能有效,因此它无法帮助我们理解 您的 代码的外观。
  • @ValentinoZaffrani 在原始代码中,block.vtx 是一个std::vector&lt;CTransactionRef&gt;,因此tx 在循环枚举vector 时推导出为const CTransactionRef&amp;。因此tx 可以分配给另一个CTransactionRef,在本例中为txNew。显然,您的代码并非如此。你的工作就是弄清楚为什么会这样。您的变量不是您期望的类型。
猜你喜欢
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 2014-07-03
  • 2017-08-15
  • 1970-01-01
相关资源
最近更新 更多