【发布时间】: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。