【问题标题】:Does std::any_cast call destructor? How the cast works?std::any_cast 是否调用析构函数?演员阵容如何?
【发布时间】:2021-06-13 12:00:04
【问题描述】:
#include <iostream>
#include <any>

using namespace std;

class c {
public:
    c() :a{ 0 } { cout << "constructor\n"; }
    c(int aa) :a{ aa } { cout << "Constructor\n"; }
    ~c() { cout << "destructor\n"; }
    int get() { return a; }
private:
    int a;
};

auto main()->int
{
    any a{ 5 };
    cout << any_cast<int>(a) << '\n';
    
    a.emplace<c>(3);
    cout << '!' << any_cast<c>(a).get() << '\n';
    //des
    cout << '\n';
    
    a.emplace<c>(9);
    cout << '!' << any_cast<c>(a).get() << '\n';
    //des
}

在每个 any_cast 之后调用的析构函数。 并且,下面的代码会导致运行时错误。 我认为原因是 any_cast(C) 的工作管道可能就像 ~C() then X(C) ERROR!!C doesn't exist any_cast 真的可以这样工作吗?

我添加了打击代码并产生了运行时错误。

class X {
public:
    X() :a{ 0 } { cout << "xonstructor\n"; }
    X(c& aa) :a{ aa.get() } { cout << "Xonstructor\n"; }
    ~X() { cout << "Xdestructor\n"; }
    int get() { return a; }
private:
    int a;
};

auto main()->int
{
    any a{ 5 };
    cout << any_cast<int>(a) << '\n';
    
    a.emplace<c>(3);
    cout << '!' << any_cast<X>(a).get() << '\n';
//runtime error after '!'
    cout << '\n';
    
    a.emplace<c>(9);
    cout << '!' << any_cast<X>(a).get() << '\n';
}

【问题讨论】:

  • a.emplace&lt;c&gt;(3); 是一个错字。你想要a.emplace&lt;X&gt;(3);
  • @super 我不认为这是一个错字……我认为 OP 打算在 any_cast 中调用转换构造函数。
  • @super 我的想法是用 3 把 a 变成 c,然后用 any_cast 用 X 把它计算出来。不是错别字

标签: c++ stdany anycast


【解决方案1】:

您正在复制来自std::any 中的c(或X)。该副本在被流出后在表达式的末尾被销毁。

any_cast 不进行任何转换。如果您要求它提供与它存储的类型不同的类型,它会抛出。当您放置了c 并要求提供X 时,它会抛出std::bad_any_cast,因为X 不是c

【讨论】:

  • 谢谢。 any_cast 只是一个取值工具。不是转换器!我说的对吗?
  • 是的,它只是用于提取存储在any中的值
猜你喜欢
  • 1970-01-01
  • 2014-05-07
  • 1970-01-01
  • 2015-04-05
  • 2017-02-27
  • 2015-09-11
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
相关资源
最近更新 更多