Mam program kde mam mnozstvo tried ktore su odvodene z bazovej triedy ktora ma atribut ID. Tento atribut moze byt typu std::string alebo int(vzdy ma len jeden typ), casom mozno bude moct mat viecej typov . Zaroven ale moze nastat moznost ze objekt nema ziadne id(porovnanie id-eciek 2 objektov kotre nemaju specifikovane id sa musy vyhodnoti ako false). Rad by som bol aby sa zbytocne nealokovala pamet na heape v std::string ak nie je treba (rychlost programu je dvolezita).
Zatial to riesim tak ze atribut ID je typu Id:
class Id{
union{
std::string name;
int key;
};
enum class type_e{
String,
Key,
Unknown
};
type_e type;
public:
Id():type(type_e::Unknown){}
Id(const std::string &name):type(type_e::String){
new(&this->name) std::string(name);
}
Id(int key):type(type_e::Key){
this->key = key;
}
Id(const Id& id){
switch(id.type){
case type_e::String:
new(&this->name) std::string(id.name);
type = type_e::String;
break;
case type_e::Key:
key = id.key;
type = type_e::Key;
break;
case type_e::Unknown:
type = type_e::Unknown;
break;
}
return;
}
Id(Id&& id){
switch(id.type){
case type_e::String:
name = std::move(id.name);
type = type_e::String;
id.type = type_e::Unknown;
break;
case type_e::Key:
key = id.key;
type = type_e::Key;
break;
case type_e::Unknown:
break;
}
return;
}
Id& operator=(const Id& id){
if(id.type != type){
//treba uplne prerobyt pri zmene type_e
if(id.type == type_e::String){
new(&this->name) std::string(id.name);
type = type_e::String;
}
else if(type == type_e::String){
name.~string();
key = id.key;
type = id.type;
}
}
else{
switch(type){
case type_e::String:
name = id.name;
break;
case type_e::Key:
key = id.key;
break;
case type_e::Unknown:
break;
}
}
return *this;
}
bool operator==(const Id& id)const{
if(id.type == type){
switch(type){
case type_e::String:
return (name == id.name);
case type_e::Key:
return (key == id.key);
case type_e::Unknown:
return false;
}
}
return false;
}
bool operator!=(const Id& id)const{
if(id.type == type){
switch(type){
case type_e::String:
return (name != id.name);
case type_e::Key:
return (key != id.key);
case type_e::Unknown:
return true;
}
}
return true;
}
~Id(){
if(type == type_e::String)name.~string();
}
};
Neda sa to riesit dako pomocou stl (pripadne boost... )? Ak nie, je ta trieda co mam dobre? (valgrind mi zatial nic nenasiel)