2 回答

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
除非定義了 const,否則無法對(duì)其進(jìn)行初始化。你必須找到一種方法來知道它的定義價(jià)值。如果 很難確定 的值,請(qǐng)考慮使用函數(shù)的結(jié)果,例如x
const int x = calc_x();
或類似的閉包
const int x = []() { /* code to calculate x's value */ }();
const
ness 是對(duì)象類型的一部分,并且對(duì)象類型在任何情況下都不能更改,因此要么是,您以后無法初始化它,要么根本不是。x
const
x
const
可以設(shè)計(jì)一個(gè)可以模擬此內(nèi)容的包裝器,但您最多只能得到一個(gè)運(yùn)行時(shí)錯(cuò)誤。class
請(qǐng)注意,似乎可能存在以下形式的解決方案,但假設(shè)所討論的對(duì)象實(shí)際上不是 。在初始化后無法合法更改其值的情況下。const_cast
const
const int x

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
C++沒有內(nèi)置功能。不過,您可以自己構(gòu)建它。您可以創(chuàng)建一個(gè)類來保存所需類型的對(duì)象的存儲(chǔ)空間,并且可以重載該對(duì)象的賦值運(yùn)算符,以便只能調(diào)用和初始化一次。這看起來像
template<typename T>
class once
{
private:
std::aligned_storage_t<sizeof(T), alignof(T)> data;
T* ptr = nullptr;
public:
once() = default;
~once()
{
if(ptr) // it is initialized so call the destructor
ptr->~T();
// optionally you can add
// throw("a once<T> must be initialized once");
// this can help to enforce that the object is actually initialized as you'll get a runtime exception in code that does not do so
}
template<typename U>
once& operator =(U&& value)
{
if (!ptr) // it is not initialized so call constructor
{
ptr = new(&data) T(std::forward<U>(value));
}
else
throw ("can only assign to a once<T> once.");
return *this;
}
operator const T&()
{
return *ptr;
}
};
然后你會(huì)像這樣使用它
int main()
{
once<int> foo;
if (1 < -1)
foo = 21;
else
foo = 42;
std::cout << foo;
//foo = 23; // uncomment this to get an exception.
}
添加回答
舉報(bào)