如何提升::变体存储引用
How does boost::variant store references?
以下代码编译并执行"正确的操作":
#include <boost/variant.hpp>
#include <iostream>
int main()
{
int a = 10;
boost::variant<int&, float&> x = a;
a = 20;
std::cout << boost::get<int&>(x) << "n";
return 0;
}
boost::变体如何存储引用?根据C++标准,引用的存储方式完全取决于编译器。实际上,boost::variant
怎么知道引用占用了多少字节?sizeof(T&) == sizeof(T)
,所以不能使用sizeof()
运算符。现在,我知道引用很可能是作为指针实现的,但在语言中没有保证。当变量存储引用时,get<>
和访问是如何工作的一个很好的解释会得到额外的分数:)
您可以将结构字段声明为引用。
struct ref_to_int {
ref_to_int(int& init)
: _storage(init) {} // _storage stores the reference.
private:
int& _storage;
};
你可以使用sizeof(ref_to_int)
,它是我的x64上的8
。该字段存储引用。
相关文章:
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- 存储对(可能)临时对象的引用是否合法,只要引用不比对象存活?
- 在C++中,如果成员引用在其声明中初始化,为什么需要存储空间?
- 我们如何在指针中存储对对象的引用?
- 如何在拥有的C++对象中安全地存储对所有者的引用?
- C++ 在节点内存储对数据对象的引用,而不复制数据
- 标准库容器结构是否存储副本或引用?
- 如果结果存储在变量中forward_as_tuple然后在 std::apply 中使用之前丢失右值引用
- 是否可以将引用存储在标准::任何中
- 在模板中存储右值引用的危险
- 通过引用传递对象并将其存储为成员变量
- 每当传递lvalue时,每当通过rvalue传递时,将const引用存储
- 按名称存储和引用变量列表
- 在类中存储引用
- 何时应存储指向函数的引用或指针?
- 在闭包中,如何通过存储在内存中的指针或引用类型捕获可变性或用现代函数式语言进行处理?
- c++存储引用返回的私有变量的正确方法
- 如何提升::变体存储引用
- 使用std::containers存储引用,gnuc++98
- 我如何设法在标准容器中存储引用类型?