c++ - 将动态分配对象传递给 boost::any 构造函数

标签 c++ boost any

#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 和 1.64 进行了测试。使用 Gcc 5.4 和 Clang。)

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

但是请注意,没有理由在那里使用 new/delete,并且在初始化 boost 后不使用 str::any,因为 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

关于c++ - 将动态分配对象传递给 boost::any 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44999345/

相关文章:

c++ - boost 协程 2 的意外输出

C++::Boost::Regex 迭代子匹配

c++ - boost directory_iterator是否在Windows上按字母顺序访问文件和文件夹

sql - SQL ANY 和 SOME 关键字在所有 SQL 方言中都是同义词吗?

ruby - '.any?' :String (NoMethodError 的未定义方法 ""

macos - macos 中 "any"伪设备的模拟

c++ - 使用虚函数 C++ 创建 Die 类

c++ - <random> 随机数生成器和均匀分布

c++ - 错误 C3861 : 'execute_assert' : identifier not found

c++ - 使用 boost-python 将参数从 Python 脚本传递到 C++