2013-01-17 30 views
2

爲什麼不能正常工作?boost :: const成員可選

struct O { 
    O(int i, int j) 
     : i(i) 
     , j(j) 
    {} 

    int const i; 
    int const j; 
}; 

int main(int argc, char** argv) 
{ 
    boost::optional<O> i; 
    i.reset(O(4, 5)); 
    return 0; 
} 

它似乎試圖使用賦值運算符而不是試圖構建它。我假定它會在未初始化的內存上調用O的拷貝構造函數。

/..../include/boost/optional/optional.hpp:433:69: error: use of deleted function ‘O& O::operator=(const O&)’ 
.... error: ‘O& O::operator=(const O&)’ is implicitly deleted because the default definition would be ill-formed: 
.... error: non-static const member ‘const int O::i’, can’t use default assignment operator 
.... error: non-static const member ‘const int O::j’, can’t use default assignment operator 

回答

1

Boost.Optional使用賦值或複製構造,具體取決於i的狀態。由於這個狀態是運行時信息,所以在分配和複製之間的選擇也必須在運行時進行。
但是,這意味着編譯器必須爲這兩個選項生成代碼,即使其中一個選項實際上未被使用。這意味着這兩種選擇都是可能的。

要獲取該代碼的工作,你可以的(總是不及格)assingment經營者添加到class O

O& O::operator=(const O&) 
{ 
    throw "this is not possible" 
    return *this; 
} 

作爲一個側面說明,Optional<T>::reset已被棄用。您應該只使用assingment,如

i = O(4,5); 

上面描述的語義對兩者均有效。

+0

在哪些情況下會使用它?當我嘗試分配給可選項時? – nishantjr

+0

@njr:當賦值給一個已經存在值的'Optional '時,將使用賦值運算符。 –

+0

Ahhh ...如果我重置了兩次,它會失敗 – nishantjr