2015-01-21 50 views
0

的成員。它有什麼問題嗎?:聯盟不會採取型「串」

_foo.cpp:6:3: error: use of deleted function 'foo::foo()' 
} bar; 
^
_foo.cpp:4:7: note: 'foo::foo()' is implicitly deleted because the default definition would be ill-formed: 
union foo { 
    ^
_foo.cpp:5:14: error: union member 'foo::dunno' with non-trivial 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string() [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' 
    std::string dunno; 
      ^
_foo.cpp: In function 'void __static_initialization_and_destruction_0(int, int)': 
_foo.cpp:6:3: error: use of deleted function 'foo::~foo()' 
} bar; 
^
_foo.cpp:4:7: note: 'foo::~foo()' is implicitly deleted because the default definition would be ill-formed: 
union foo { 
    ^
_foo.cpp:5:14: error: union member 'foo::dunno' with non-trivial 'std::basic_string<_CharT, _Traits, _Alloc>::~basic_string() [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' 
    std::string dunno; 
      ^
_foo.cpp: In function 'void __tcf_1()': 
_foo.cpp:6:3: error: use of deleted function 'foo::~foo()' 
} bar; 
^

你能解釋一下,爲什麼?

回答

9

C++ 11確實引入了在工會中包含任意類型的可能性。但是,您需要向工會提供這些類型所有的特殊成員函數。它很好地總結了C++ 11 9.5/2:

[注:如果工會的任何非靜態數據成員有一個不平凡的默認 構造函數(12.1),拷貝構造函數(12.8) ,移動構造函數(12.8),複製賦值運算符(12.8),移動 賦值運算符(12.8)或析構函數(12.4),聯合的相應成員函數必須是用戶提供的 或將被隱式刪除(8.4。 3)爲工會。 末端注]

這意味着,如果你希望你的工會有一個默認的構造函數,你必須定義它,像這樣:

union foo { 
    std::string dunno; 
    foo() : dunno() {} 
} bar; 
0

C++ 03標準禁止使用的類型在union中使用的非平凡構造函數(std::string構造函數是非平凡的)。這個限制在C++ 11中被刪除了。 此外,如果union具有非平凡構造函數的成員,您還需要定義構造函數。