考虑下面的三个代码块,这是字符串/union 冲突的三种替代解决方案。
在这些选项中,一般来说,以这种方式使用 union 的内存效率更高?
我正在寻找解决原则的答案:也就是说, union 的主要目的是节省内存。
编辑:类作业迫使我以这种方式使用 union 。它让我思考哪一个是最有效的,这就是我到达这里的原因。
代码块(A):
// unions with pointers to structs
struct HourlyInfo {
string firstName;
string lastName;
string title;
int hoursWorked;
double hourlyRate;
};
struct SalaryInfo {
string firstName;
string lastName;
string title;
double salary;
double bonus;
};
struct Employee {
bool isHourly;
union {
HourlyInfo *hourlyEmployee;
SalaryInfo *salaryEmployee;
}
};
代码块(B):
// applying unions to relevant and non-string data types
struct Employee {
string firstName;
string lastName;
string title;
bool isHourly;
union {
struct {
double hourlyRate;
int hoursWorked;
} hourly;
struct {
double salary;
double bonus;
} salaried;
};
};
代码块(C):
// use cstring instead of string
struct HourlyInfo {
cstring firstName[50];
cstring lastName[50];
string title[50];
int hoursWorked;
double hourlyRate;
};
struct SalaryInfo {
cstring firstName[50];
cstring lastName[50];
cstring title[50];
double salary;
double bonus;
};
struct Employee {
bool isHourly;
union {
HourlyInfo hourlyEmployee;
SalaryInfo salaryEmployee;
}
};
(注意:代码背后的想法是,任何员工要么是小时工,要么是工资,因此这里有 union 。请不要针对这个问题提出不涉及 union 的替代解决方案。我不担心解决具体问题,我对 union 感兴趣。)
此外,指针和其他数据类型的大小似乎差异很大:
What does the C++ standard state the size of int, long type to be?
How much memory does a C++ pointer use?
这是否意味着我们无法对内存效率做出一揽子声明?如果是这样,我们在确定最有效的方法时应该考虑哪些因素?
最佳答案
规则 #1:遵循您的分析器(它会告诉您哪一个对您的程序更有效)
规则#2:关于内存分配:使用自定义分配器来隐藏复杂性
规则 #3:设计数据类型以清晰表达意图/目的(从这个意义上说,只有 B 是一个选项)。当然,除非规则 #1 需要再次采取(这很不寻常)
我知道我“不允许”提出替代方案:( Live on Coliru )
#include <string>
#include <boost/variant.hpp>
struct HourlyInfo {
int hoursWorked;
double hourlyRate;
};
struct SalaryInfo {
double salary;
double bonus;
};
namespace detail {
template <template <typename...> class Allocator = std::allocator>
struct basic_employee {
using string = std::basic_string<char, std::char_traits<char>, Allocator<char>>;
string firstName;
string lastName;
string title;
using RateInfo = boost::variant<HourlyInfo, SalaryInfo>;
RateInfo rates;
};
}
using Employee = detail::basic_employee<>; // or use a custom (pool?) allocator
int main()
{
Employee staff1 = {
"John", "Cage", "From accounting",
SalaryInfo { 1900.00, 120.0 }
};
Employee contractor = {
"Joe", "Duffy", "Plumbing jobs",
HourlyInfo { 3, 46.00 }
};
}
关于c++ - 关于 C++ 中 union 使用的内存效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19611235/