【问题标题】:Passing dynamic allocating object into boost::any constructor将动态分配对象传递给 boost::any 构造函数
【发布时间】:2017-07-09 17:52:19
【问题描述】:
#include <iostream>
#include <boost/any.hpp>

class Str
{
public:
  // default constructor
  Str() : str_{"Hello, World!"} { std::cout << "A::A()" << this << std::endl;  }

  // copy constructor
  Str(const Str& that) : str_(that.str_) { std::cout << "A::A(const A&)" << this << std::endl; }
  Str(Str& that) : str_(that.str_) { std::cout << "A::A(A&)" << this << std::endl; }

  // move constructor
  Str(const Str&& that) : str_(std::move(that.str_)) { std::cout << "A::A(const A&&)" << this << std::endl; }
  Str(Str&& that) : str_(std::move(that.str_)) { std::cout << "A::A(A&&)" << this << std::endl; }
  // destructor
  ~Str() { std::cout << "~A::A()" << this << std::endl; }

  // str print method
  void print() const { std::cout << str_ << '\n'; }

private:
  std::string str_;
};

int main(int argc, char *argv[])
{
  auto* str = new Str;
  boost::any a(*str);
  if (a.empty()) {
    std::cout << "empty\n";
  } else {
    std::cout << "not empty\n";
  }
  auto s = boost::any_cast<Str>(&a);
  std::cout << s << std::endl;
  std::cout << a.empty() << std::endl;
  delete str;
  return 0;
}

这个简单的程序有输出:

A::A()0x24f5c20
not empty
0
0
~A::A()0x24f5c20

因此,要正确理解它,正确的程序输出需要是:

A::A()0x24f5c20
A::A(const A&)some address // copy str before passing into any constructor
not empty 
some address 
0 
~A::A()some address //~any() call ~A()some address
~A::A()0x24f5c20

看起来不明白发生了什么。 那是用 g++ 版本 5.4.0 编译的。 人们!我是怎么了? =)

【问题讨论】:

  • 我无法重现。您使用的是哪个版本的 Boost?
  • 我使用的是 1.62 版本的 boost。

标签: c++ boost any


【解决方案1】:

我将假设您正在运行旧版本的程序或未正确重建它。 (我用 boost 1.62 和 1.64 测试过。使用 Gcc 5.4 和 Clang。)

该程序具有预期的效果,并且不会调用任何类型的未定义行为。

但是请注意,没有理由在那里使用new/delete,并且在初始化boost::any 后不会使用str,因为boost::any 存储值 - 从不引用。因此,您可以简单地说

auto *str = new Str;
boost::any a(*str);
delete str;

或者只是

Str str;
boost::any a(str);

甚至

boost::any a(Str{}); // beware of "most vexing parse"

你可以比较东西Live On Coliru

【讨论】:

    猜你喜欢
    • 2018-04-13
    • 2014-06-04
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2012-07-09
    • 2011-10-24
    相关资源
    最近更新 更多