2017-07-09 4 views
1
#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 
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 

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

だから、右のそれを理解するために、正しいプログラムの出力は次のようにする必要があります

何が起こっているのか分かりません。 g ++バージョン5.4.0でコンパイルされました。 人!私は一体どうしたんだろう? =)

+0

を比較することができ

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" 

を言うことができます。 Boostのどのバージョンを使用していますか? –

+0

私は1.62バージョンのブーストを使用しています。 –

答えて

0

古いバージョンのプログラムを実行している、または正しく再構築していないと仮定します。 (私はboost 1.62と1.64でGcc 5.4とClangを使ってテストしました)

このプログラムは、意図した効果を持ち、未定義の動作を引き起こしません。

注しかし、そこnew/deleteを使用する理由がないこと、およびstrboost::any値を格納するために、boost::anyを初期化した後に使用されていない - 決して言及。このため、単にあなたが、私はそれを再現することはできませんものLive On Coliru

関連する問題