我在使用 emplace_back 在向量中構造位域結構時遇到此錯誤:
struct Foo
{
Foo(uint32_t foo1): foo1(foo1) {}
uint32_t foo1 : 4;
};
int main()
{
vector<Foo> fooVector;
Foo foo = Foo(10);
fooVector.emplace_back(foo.foo1); // Error: non-const reference cannot bind to bit-field
}
我發現我可以通過使用 push_back (但出于性能原因我更喜歡 emplace_back )或像這樣修改相關行來避免此錯誤:
fooVector.emplace_back(uint32_t(foo.foo1)); // Don't raise error
這是處理它的正確方法嗎?為什么這個解決方案有效?
uj5u.com熱心網友回復:
這是 的定義std::vector::emplace_back:
template< class... Args >
reference emplace_back( Args&&... args );
Args&&在這種情況下被推導為uint32_t&,并且正如錯誤所說,位域 ( Foo::foo1) 不能系結到這種型別,因為它是一個非常量參考。
通常,您不能擁有指向位域的參考或指標,因為它沒有地址。const 參考之所以有效,是因為它創建了一個使用位域的值進行副本初始化的臨時物件,并改為系結到該臨時物件。
您確實可以進行中間轉換,就像在您的示例中或更明確地這樣:
fooVector.emplace_back(static_cast<uint32_t>(foo.foo1));
但是,我質疑為什么您想要 a 的 8 位位域uint32_t而不是僅使用uint8_t.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513845.html
標籤:C C 17
