For example, I create a singleTon lock class. Then I use the locker whatever I want, for example another singleTon
class SIN
{
public:
static SIN& getSIN()
{
static SIN *sin = new SIN;
return *sin;
}
void insertMap(const int& id,const string& str)
{
locker::getLocker().lock();
subMap[id] = str;
locker::getLocker().unlock();
return;
}
string getStr(const int& id)
{
string str = "";
locker::getLocker().lock();
if(subMap.find(id) != subMap.end()){
str = subMap[id];
}
locker::getLocker().unlock();
return str;
}
private:
SIN(){}
SIN(const SIN&) = delete;
SIN& operator=(const SIN&) = delete;
private:
map<int,string> subMap;
}
I don't find this usage in network, will there be any potential problems during using?
Related
I have to do a little c++ reflection in my way, by creating a pointer for each property of my class(I have create a tool to help me generate corresponding c++ code), but surprise, Building on x86 mode worked fine, but on x64 mode it's crashed, I have no idea why! here is my code.
Product.h File
class Product
{
public:
int ID;
std::string Designation;
};
class Property
{
public:
std::string Name;
int Shift;
};
class ProductSchema
{
private:
ProductSchema();
public:
static ProductSchema* Default();
ProductSchema(const ProductSchema& other) = delete;
Property ID;
Property Designation;
Property Prix;
};
Product.cpp File
ProductSchema::ProductSchema()
{
Product* p = new Product();
ID.Name = "ID";
ID.Shift = (int)(int*)&p->ID - (int)p;
Designation.Name = "Designation";
Designation.Shift = (int)(int*)&p->Designation - (int)p;
}
ProductSchema* ProductSchema::Default()
{
static ProductSchema* instance_;
if (instance_ == nullptr)
instance_ = new ProductSchema;
return instance_;
}
main.h file
int main()
{
for (int i = 0; i < 10000; i++)
{
Product* p = new Product();
int* pID = (int*)((unsigned long int)p + ProductSchema::Default()->ID.Shift);
*pID = i; // <--- error here
}
}
Your ProductSchema class, and your main(), are leaking the objects they new.
You don't need to create an object at runtime to calculate offsets to its members, you can use offsetof() at compile-time instead.
Don't use int or unsigned long to perform calculations on pointers. They are not guaranteed to be large enough. Use (u)intptr_t instead.
Your singleton is not initializing its instance_ pointer before using it. It does not need to use dynamic memory at all.
Try this instead:
class Product
{
public:
int ID;
std::string Designation;
};
struct Property
{
std::string Name;
int Shift;
};
class ProductSchema
{
private:
ProductSchema();
public:
static ProductSchema& Default();
ProductSchema(const ProductSchema& other) = delete;
Property ID;
Property Designation;
Property Prix;
};
ProductSchema::ProductSchema()
{
ID.Name = "ID";
ID.Shift = offsetof(Product, ID);
Designation.Name = "Designation";
Designation.Shift = offsetof(Product, Designation);
}
ProductSchema& ProductSchema::Default()
{
static ProductSchema instance_;
return instance_;
}
int main()
{
for (int i = 0; i < 10000; i++)
{
Product p;
int* pID = reinterpret_cast<int*>(reinterpret_cast<uintptr_t>(&p) + ProductSchema::Default().ID.Shift);
*pID = i;
}
}
Online Demo
I have an UserAcount class that has an abstract class ContBancar, and other class Banca which reads some users from a file (with method void Banca::citire_conturi()). When it reads the users, I get an error "Access violation writing location" in ContBancar at void setBal(double bal) { _balanta = bal; }. Thx for help !
PS : The file has only one line : 1CBS Dragos 0 dragos12! Gzpvia01= .
Also, i want to make a bank account system, with an user class that has an bank account class which inherits 3 types of a bank accounts, and a bank class which reads some users from a file or put them on it.
class UserAccount
{
private:
std::string _nume, _user, _pass;
std::string _cod_us;
std::shared_ptr <ContBancar> _cont;
public:
void setUser(std::string user) { _user = user; }
void setPass(std::string pass) { _pass = pass; }
void setNume(std::string nume) { _nume = nume; }
void setCodUs(std::string cod) { _cod_us = cod; }
void setContBal(double balanta) { (*_cont).setBal(balanta); }
std::string getUser() const { return _user; }
std::string getPass() const { return _pass; }
std::string getNume() const { return _nume; }
std::string getCodUs() const { return _cod_us; }
double getContBal() const { return (*_cont).getBal(); }
void setContBancar();
};
void UserAccount::setContBancar()
{
if (_cod_us == "1CBS")
_cont.reset(new ContBancarSilver());
else if (_cod_us == "2CBG")
_cont.reset(new ContBancarGold());
else
_cont.reset(new ContBancarDiamond());
}
class ContBancar
{
protected:
double _balanta;
public:
void setBal(double bal) { _balanta = bal; }
double getBal() { return _balanta; }
virtual bool depozitare(unsigned int) = 0;
virtual bool retragere(unsigned int) = 0;
};
class Banca
{
private:
std::vector<UserAccount> vec;
public:
void citire_conturi();
};
void Banca::citire_conturi()
{
std::ifstream file;
file.open("Baza_Date.txt");
UserAccount temp;
std::string cod, nume, user, pass;
double balanta;
while (file >> cod >> nume >> balanta >> user >> pass)
{
temp.setCodUs(cod);
temp.setNume(nume);
temp.setContBal(balanta);
temp.setUser(user);
temp.setPass(pass);
vec.push_back(temp);
}
file.close();
}
class ContBancarSilver : public ContBancar
{
private:
static constexpr unsigned int max_balanta = 5000;
static constexpr unsigned int max_depozitare = 2500;
static constexpr unsigned int max_retragere = 1000;
static constexpr double tax_retragere = 0.08;
static constexpr double bonus_depunere = 0.03;
static constexpr double bonus_tax_retragere = 0.05;
static constexpr unsigned int max_depozitari = 1;
static constexpr unsigned int max_retrageri = 1;
public:
virtual bool depozitare(unsigned int) override;
virtual bool retragere(unsigned int) override;
};
Based on available informationyou should fix your code like this:
class UserAccount
{
.....
void setCodUs(std::string cod) {
_cod_us = cod;
setContBancar();
}
void setContBal(double balanta) {
if (!_cont) setContBancar(); // lazy initialization
_cont->setBal(balanta);
}
...
};
void UserAccount::setContBancar()
{
if (_cod_us == "1CBS")
_cont = std::make_shared<ContBancarSilver>();
else if (_cod_us == "2CBG")
_cont = std::make_shared<ContBancarGold>();
else
_cont = std::make_shared<ContBancarDiamond>();
}
Note I do not understand what kind of logic you are implementing. This changes just ensured that _cont is initialized and up to date with _cod_us.
Please stop use explicitly new and delete. Everything can be created by std::make_shared and std::make_unique and containers like std::vector.
I want Swap the name (i.e. string in cName[]) of the two cats using the pointer approach.
However I want to Only swap the name, NOT the object.
Am I correct?
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string.h>
using namespace std;
class CAT
{
public:
CAT(char * firstname) { strncpy(cName, firstname, 79); }
~CAT() { ; }
char * getName() { return cName; }
void setName(char *nameinput) { strncpy(cName, nameinput, 79); }
private:
char cName[80];
};
void nameSwap(CAT *CatA, CAT *CatB)
{
char testing[] = "testing";
CAT temp =CAT(testing);
temp = *CatA;
*CatA = *CatB;
*CatB = temp;
}
int main()
{
char Taby[] = "Taby";
char Felix[] = "Felix";
CAT pA = CAT(Taby);
CAT pB = CAT(Felix);
cout << "The inital name pA is " << pA.getName() << " and pA is" << pB.getName() << endl;
nameSwap(&pA, &pB);
cout << "After approach" << endl;
cout << "The name pA is " << pA.getName() << " and " << pB.getName() << endl;
system("PAUSE");
return 0;
}
You are actually swapping the whole objects, not only the name of the CAT.
If you only want to swap the name, you need to access the cName member in a similar way as you are doing for the objects. You'd also need permission to access to the cName member in such a swap function, which a function outside won't have since cName is private. Make the swap function a member of your class:
class CAT
{
public:
CAT(const char* firstname) { strncpy(cName, firstname, 80); }
~CAT() {}
const char* getName() const { return cName; }
void setName(const char *nameinput) { strncpy(cName, nameinput, 80); }
void swapName(CAT& CatB)
{
char tmp[80];
strncpy(tmp, CatB.cName, 80);
strncpy(CatB.cName, cName, 80);
strncpy(cName, tmp, 80);
}
private:
char cName[80];
// other CAT attributes won't be affected by the name swap
};
And call it like this
pA.swapName(pB); // or pB.swapName(pA); - same result
But consider using std::string instead of char[]. You'll soon find C++ strings much easier to work with and also, when swapping those, only the pointers to the underlying memory is swapped, so it's more effective.
std::string one;
std::string two;
one.swap(two);
Edit: As per request, I added a version using pointers.
I made it in a haste and haven't debugged it so I've probably made a lot of mistakes. First, I made a new class called wong_string that will hold the name and any other attributes suiteable for strings.
#include <stdexcept>
#include <cstring>
class wong_string {
char* m_data;
static char* duplicate(const char* str) {
size_t len = std::strlen(str)+1;
char* rv = new char[len];
std::memcpy(rv, str, len);
return rv;
}
public:
// default constructor: wong_string howdy1;
wong_string() : m_data(nullptr) {}
// conversion constructor: wong_string howdy2("value2");
wong_string(const char* cstr) :
m_data(duplicate(cstr))
{}
// copy constructor: wong_string howdy3 = howdy2;
wong_string(const wong_string& rhs) : wong_string(rhs.m_data) {}
// move constructor: wong_string howdy4 = wong_string("value4");
wong_string(wong_string&& rhs) : m_data(rhs.m_data) {
rhs.m_data = nullptr;
}
// copy assignment operator: (wong_string howdy5;) howdy5 = howdy4;
wong_string& operator=(const wong_string& rhs) {
if(this!=&rhs) {
char* tmp = duplicate(rhs.m_data);
if(m_data) delete []m_data;
m_data = tmp;
}
return *this;
}
// copy assignment operator from c string
wong_string& operator=(const char* rhs) {
*this = wong_string(rhs);
return *this;
}
// move assignment operator: (wong_string howdy6;) howdy6 = wong_string("value6");
wong_string& operator=(wong_string&& rhs) {
if(this!=&rhs) {
m_data = rhs.m_data;
rhs.m_data = nullptr;
}
return *this;
}
// destructor, free memory allocated by duplicate(), if any
~wong_string() {
if(m_data) delete []m_data;
}
// comparisons
bool operator==(const wong_string& rhs) const {
return strcmp(m_data, rhs.m_data)==0;
}
bool operator!=(const wong_string& rhs) const {
return !(*this==rhs);
}
// conversion to a normal c string
operator char const* () const { return m_data; }
// output stream operator
friend std::ostream& operator<<(std::ostream&, const wong_string&);
// input stream operator - not implemented yet
};
with that in place, your CAT can be made into something like this:
class CAT
{
public:
CAT(const char* firstname, const char* nickname=nullptr) :
cName(firstname),
cNickName(nickname?nickname:firstname)
{}
~CAT() {}
const char* getName() const { return cName; }
void setName(const char *nameinput) { cName=nameinput; }
void swapName(CAT& CatB)
{
std::swap(cName, CatB.cName);
}
private:
wong_string cName; // Madame Florence Jenkins III
// other CAT attributes won't be affected by the name swap
wong_string cNickName; // Ms. Miao
};
So, there you have it. Pointers galore...
I have a class that contain some game level settings.
class Stage {
private:
int level;
int stars;
std::string imgName;
public:
int getLevel(){ return level; };
void setLevel(int n){ level = n; };
int getStars(){ return stars; };
void setStars(int n){ stars = n; };
std::string getImgName(){ return imgName; };
void setImgName(std::string name){ imgName = name; };
};
Then in my program I set the info.
Stage* stagesArr = new Stage[3];
stagesArr[0].setLevel(0);
stagesArr[0].setStars(1200);
stagesArr[0].setImgName("stage0.png");
Then if I want to get this info the string is giving me an odd output.
CCLOG("Level: %i", stagesArr[0].getLevel());
CCLOG("Required stars: %i", stagesArr[0].getStars());
CCLOG("Image Name: %s", stagesArr[0].getImgName());
//Level:0
//Required stars: 1200
//Image Name: T%s //Or just random stuff.
What am I missing here?
Suspected that CCLOG() uses the same formatting rules like the <x>printf() function family does, you need to pass a const char* with the format specifier %s.
Your getImgName() returns a std::string value though, which isn't directly compatible with a const char*.
To achieve the latter, you should call the std::string::c_str() function:
CCLOG("Image Name: %s", stagesArr[0].getImgName().c_str());
Also you can improve your getter/setter functions specifying constness applicability more clear:
int getLevel() const { return level; }
// ^^^^^^
int getStars() const { return stars; }
// ^^^^^^
const std::string& getImgName() const { return imgName; }
// ^^^^^ // ^^^^^^
void setImgName(const std::string& name) { imgName = name; }
// ^^^^^
Note:
As a matter of style you can omit the get / set prefixes for getter/setter functions in c++, as the signatures are disambiguate enough:
int Level() const { return level; }
void Level(int n){ level = n; }
int Stars() const { return stars; }
void Stars(int n){ stars = n; }
const std::string& ImgName() const { return imgName; }
void ImgName(const std::string& name){ imgName = name; }
My personally preferred style is to use lower caps and disambiguate class member variables with a _ postfix:
class Stage {
private:
int level_;
int stars_;
std::string img_name_;
public:
int level() const { return level_; }
void level(int n) { level_ = n; }
int stars() const { return stars_; }
void stars(int n){ stars_ = n; }
const std::string& img_name() const { return img_name_; }
void img_name(const std::string& name) { img_name_ = name; };
};
I get a segmentation fault when i try to insert into my map.
The function looks something like this:
void add(std::string id, std::string name)
{
Asset asset(nullptr, false, name);
mAssets.insert(std::make_pair<std::string, Asset>(id,asset)); <-- This line gives segfault
}
mAssets is simply declared
std::map<assetID, Asset> mAssets;
And the Asset class is (sloppy) declared like this:
class Asset
{
public:
Asset(T* a, bool l, std::string f) : asset(a), loaded(l), filename(f)
{
}
Asset(const Asset& copy)
{
loaded = copy.loaded;
filename = copy.filename;
asset = new T();
*asset = *copy.asset;
}
~Asset()
{
delete asset;
}
Asset& operator=(const Asset& other)
{
Asset temp(other);
loaded = temp.loaded;
filename = temp.filename;
std::swap(asset,temp.asset);
return *this;
}
T* asset;
bool loaded;
std::string filename;
};
Your problem is here in your copy constructor:
asset = new T();
*asset = *copy.asset;
I will leave it to you to work out why...
On your copy constructor you are derefferencing a null pointer:
*asset = *copy.asset
from
Asset asset(nullptr, false, name);
Verify your pointers asigments and avoid dereferencing null pointers:
Asset(const Asset& copy)
{
loaded = copy.loaded;
filename = copy.filename;
if (copy.asset)
{
asset = new T(); // better may be asset = new T(copy)
*asset = *copy.asset;
}
else
{
asset = nullptr
}
}
*asset = *copy.asset; //you should check whether asset is NULL or not then check for asset
This is how your code will work:
#include <iostream>
#include <map>
using namespace std;
template<class T>
class Asset
{
public:
Asset(T* a, bool l, std::string f) : asset(a), loaded(l), filename(f)
{
}
Asset(const Asset& copy)
{
cout<<"copy"<<endl;
loaded = copy.loaded;
filename = copy.filename;
asset = new T();
if(© != NULL)
{
if(copy.asset != NULL)
*asset = *(copy.asset);
}
}
~Asset()
{
delete asset;
}
Asset& operator=(const Asset& other)
{
Asset temp(other);
loaded = temp.loaded;
filename = temp.filename;
std::swap(asset,temp.asset);
return *this;
}
T* asset;
bool loaded;
std::string filename;
};
std::map <string,Asset<int> > mAssets;
void add(std::string id, std::string name)
{
Asset<int> asset(NULL, false, name);
mAssets.insert(std::make_pair<std::string, Asset<int> >(id,asset)); //<-- This line gives segfault
}
int main()
{
add("1","hi");
cout<<"run"<<endl;
}