Macro for auto destroy heap objects - c++

This is not the actual code what I'm working. but this code can be used to explain my problem in clear.
I have a function called "OnCallFunction" with some new'd objects as inputs that should be deleted inside the "OnCallFunction". In each and every point i should return, i need to add the deletion code there. I think this is not the correct way of doing this. In this way this should be remembered and put in each return which will be done in future as well. If the code is not simple as below, I may forget to insert the deletion part as well.
#include <iostream>
#include <stdlib.h>
using namespace std;
class Student
{
public:
Student(){}
~Student(){}
int GetID(){return rand();}
};
int OnCallFunction(Student* pStudent)
{
int iValue = pStudent->GetID();
if (iValue == 5)
{
delete pStudent;
return 90;
}
if (iValue == 67)
{
delete pStudent;
return 8709;
}
if (iValue == 234)
{
delete pStudent;
return 78;
}
if (iValue == 343)
{
delete pStudent;
return 9832;
}
if (iValue == 678)
{
delete pStudent;
return 876;
}
delete pStudent;
return -1;
};
int main(int argc, const char** argv)
{
Student* pStudent = new Student();
OnCallFunction(pStudent);
};
So, I played around and developed a macro for auto destroy the heap objects.
This is the modified code using the macro (AUTO_DESTROY)
#include <iostream>
#include <stdlib.h>
using namespace std;
#define AUTO_DESTROY(ClassType, Variable, DeleteStatement)\
class AD##ClassType##Variable\
{\
public:\
AD##ClassType##Variable(ClassType* pData) {Variable=pData;};\
~AD##ClassType##Variable() {DeleteStatement;};\
private:\
ClassType* Variable;\
};\
AD##ClassType##Variable oAD##ClassType##Variable(Variable)
class Student
{
public:
Student(){}
~Student(){}
int GetID(){return rand();}
};
int OnCallFunction(Student* pStudent)
{
AUTO_DESTROY(Student, pStudent, delete pStudent);
int iValue = pStudent->GetID();
if (iValue == 5)
{
return 90;
}
if (iValue == 67)
{
return 8709;
}
if (iValue == 234)
{
return 78;
}
if (iValue == 343)
{
return 9832;
}
if (iValue == 678)
{
return 876;
}
return -1;
};
int main(int argc, const char** argv)
{
Student* pStudent = new Student();
OnCallFunction(pStudent);
};
Now my questions are,
1) Does this has any performance/maintainability/code quality impact rather than deleting in each return?
2) In this macro it creates a class inside the function. So will than cause multiple declarations if we use the same macro, same class type, same variable name in multiple cpp files? Agree that I can test it.
3) Are there any ideas or pre-built things to do this in easier way?
NB:
Please do not propose to create "Student" as a stack variable in heap or keep the function output in a variable and return only at the end. :)

Don't use a macro, and don't use raw pointers. Use a unique_ptr to hold the allocated object, and change your function to:
int OnCallFunction(std::unique_ptr<Student> pStudent)
{
int iValue = pStudent->GetID();
if (iValue == 5)
{
return 90;
}
if (iValue == 67)
{
return 8709;
}
if (iValue == 234)
{
return 78;
}
if (iValue == 343)
{
return 9832;
}
if (iValue == 678)
{
return 876;
}
return -1;
};
int main(int argc, const char** argv)
{
std::unique_ptr<Student> pStudent(new Student());
OnCallFunction(std::move(pStudent));
};
Proper deletion of the managed Student object will be automatically done when OnCallFunction() exits.

boost's scope exit has implemented the functionality you want. You can look into that implementation or use it out of the box.
Example :
#include <boost/scope_exit.hpp>
#include <cstdlib>
#include <cstdio>
#include <cassert>
int main()
{
std::FILE* f = std::fopen("example_file.txt", "w");
assert(f);
BOOST_SCOPE_EXIT(f) {
// Whatever happened in scope, this code will be
// executed and file will be correctly closed.
std::fclose(f);
} BOOST_SCOPE_EXIT_END
// Some code that may throw or return.
// ...
}
Using this functionality, you'd be practically specifying freestanding "RAII destructor actions".
Use where it makes your code clearer and cleaner and avoid when all functionality would be more easily incorporated (or already is) inside a class' destructor.

Related

Member function doesn't work when using pointer to class

Scenario: I have two classes, each contains a pointer to the other (when using them, being able to refer to the other is going to be important so I deemed this appropriate). When I try accessing a private variable from one class via using the pointer to the other and a getter function inside that, it works perfectly.
Problem: Using a setter (in this case, addPoints)/manipulating the variables however leads to no result.
I'm new so anything here might be "improper etiquette" and bad practice. Feel free to point them out! But please also try to provide a solution. This is also my first question on SO, so please be gentle!
Related code pieces:
Team.h
#include "Driver.h"
using namespace std;
class Team {
int Points = 0;
vector<Driver*> Drivers;
public:
void addPoints(int gained); //does not work
int getPoints(); //works perfectly
Driver getDriver(int nr);
void setInstance(vector<Driver*> drivers);
};
Team.cpp
#include "Team.h"
#include "Driver.h"
using namespace std;
void Team::addPoints(int gained) {
this->Points = this->Points + gained;
}
int Team::getPoints() {
return this->Points;
}
Driver Team::getDriver(int nr) {
return *Drivers[nr];
}
void Team::setInstance(vector<Driver*> drivers) {
this->Drivers = drivers;
}
Driver.h
using namespace std;
class Team;
class Driver {
int Points = 0;
Team* DriversTeam;
public:
void SetTeam(Team& team);
Team getTeam();
int getPoints(); //works
void addPoints(int gained); //doesn't work
};
Driver.cpp
#include "Driver.h"
#include "Team.h"
using namespace std;
void Driver::SetTeam(::Team& team) {
this->DriversTeam = &team;
}
Team Driver::getTeam() {
return *DriversTeam;
}
int Driver::getPoints() {
return this->Points;
}
void Driver::addPoints(int gained) {
this->Points = this->Points + gained;
}
Initializer.cpp (linking drivers to teams)
void InitializeData(vector<Team>& teams, vector<Driver> &drivers) {
//(...)
//reads each team in from data file to memory
//key part:
vector<Driver*> teamsDrivers;
for (auto& iter : drivers) { //this loop mainly determines which driver to link with which teams
if (iter.getName().compare(values[4]) == 0) { //values is csv line data in a string vector. I guess not the prettiest parsing method here but will be revised
teamsDrivers.push_back(&iter);
}else if(iter.getName().compare(values[5]) == 0) {
teamsDrivers.push_back(&iter);
}
}
tempTeam.setInstance(teamsDrivers);
teams.push_back(tempTeam);
}
(linking driver to team)
//drivers are linked to teams last, as they are declared first (so I cannot link them to the yet nonexisting teams)
void LinkTeam(vector<Driver>& drivers, vector<Team>& teams) {
for (auto& driverIter : drivers) { //iterate through drivers
for (auto& teamIter : teams) { // iterate through teams
bool found = 0;
for (size_t i = 0; i < teamIter.DriverAmount(); i++) {
if (driverIter.getName() == teamIter.getDriver(i).getName()) {
driverIter.SetTeam(teamIter);
found = 1;
break;
}
}
if (found) { //exit iterating if driver is found
break;
}
}
}
}
Example of use in main.cpp
teams[0].addPoints(10);
drivers[3].getTeam().addPoints(15); //driver 3 is linked to team 0
cout << teams[0].getPoints(); //15
cout << drivers[3].getTeam().getPoints(); //15
teams[0].getDriver(1).addPoints(20); //driver 1 of team 0=driver[3]
drivers[3].addPoints(25);
cout << drivers[3].getPoints(); //25
cout << teams[0].getDriver(1).getPoints(); //25
Thanks for the help in advance.
This is quite simple:
Your getTeam() and getDriver() functions are returning copies of the objects, not references, so the addPoints() are performed on temporary copies and not the real ones.
To fix it, simply change the return types to references (add &):
Team& getTeam();
and
Driver& getDriver();

Vector losing contents between files in C++

I have some methods in lexer.h which make use of a Vector made of Tokens.
In this method void getNextToken() I am making use of the said vector where I am adding new tokens to it.
The problem is, that when I go to a different file, I am trying to access ANOTHER method which makes use of this vector, but it is crashing with an out of bounds error (most probably it's being deferenced or something)
Is there a way how I can fix this?
The methods in concern are:
Token* nextToken()
{
if (it!= tokensUsed.end())
{
// we Assigned what is found in the iterator it (of the vector)
// so we get the data found in that pointer
itrToken = &*it;
//Move Iterator forward
it ++;
return itrToken;
}
}
/*
Used in Parser to go get the PREVIOUS Tokens
*/
Token* prevToken()
{
itrToken --;
if (it!= tokensUsed.begin())
{
itrToken = &*this->it;
return itrToken;
}
}
void getNextToken()
{
//CODE ADDING TOKENS
//EXAMPLE
if (ch == '"')
{
addAndGetNext(ch);
cout << "STRING: " << strBuffer << endl; //TEST
//create new token and push it into the vector
tk = new Token (Token::ttString, strBuffer, row, col);
tokensUsed.push_back(*tk); //Add the new token to the Vector
startNewString(); //Clear the string
}
tokenMatch = true;
}
The above is just partial code, to show an example.
Now in Parser.h I am using this method to call the lexer.h:
void relOpP()
{
Token* tk = nextToken();
if (tk -> getType() == Token::ttString)
{
cout << "Ture";
}
}
which calls the Lexer's nextToken() it crashes, and when I tried checking it's contents it goes outofBounds error (and CodeBlocks giving me a SIGSEGV error)
I know it's something from the pointers that it's going awry, but how can I fix it?
Edit:
These are the global variables I have declared:
vector<Token>::iterator it;
vector<Token> tokensUsed;
Token* itrToken; // used for iterator
bool checkQuote = false;
Token* tk = new Token (syNewToken, "", 1,0);
Token token; // Creates an instance of the class Token found in the file token.h
Token* t;
SAMPLE CODE:
main.cpp
#include <iostream>
#include "lexer.h"
#include "parser.h"
using namespace std;
int main()
{
Lexer* l;
l -> getNextToken();
Parser p(l);
p.relOpP();
}
Token (int type, string sBuffer, int rRow, int cCol)
{
this->tType = type;
this->strBuffer = sBuffer;
this->row = rRow;
this->col = cCol;
}
parser.h
#ifndef PARSER_H_INCLUDED
#define PARSER_H_INCLUDED
#include <string>
#include <vector>
#include "lexer.h"
#include "token.h"
using namespace std;
class Parser{
private:
Lexer* lexer;
string tree = "";
public:
Parser (Lexer* l)
{
this -> lexer = l;
}
Token nextToken()
{
Token tk = lexer -> nextToken();
return tk;
}
void relOpP()
{
Token tk = nextToken();
if (tk.getType() == 1)
{
cout << "Ture";
}
}
#endif // PARSER_H_INCLUDED
};
token.h
#ifndef TOKEN_H_INCLUDED
#define TOKEN_H_INCLUDED
#include <iostream>
using namespace std;
class Token
{
private:
int tType; //identifier or reserved by compiler?
string strBuffer; //string found in buffer at that moment
int row;
int col;
public:
enum tokenType
{
tkString
};
Token()
{
}
// The instance of a token with 4 parameters resulting the type, the contents of the string that represents that type
// the row it is found in and the column.
Token (int type, string sBuffer, int rRow, int cCol)
{
this->tType = type;
this->strBuffer = sBuffer;
this->row = rRow;
this->col = cCol;
}
Token (Token* getT)
{
this-> tType = getT -> tType;
this->strBuffer = getT -> strBuffer;
this->row = getT -> row;
this->col = getT -> col;
}
int getType ()
{
return this->tType;
}
//return the string contents
string getBuffer()
{
return this->strBuffer;
}
//return row
int getRow()
{
return row;
}
//return col
int getCol ()
{
return col;
}
};
#endif // TOKEN_H_INCLUDED
Lexer.h
#ifndef LEXER_H_INCLUDED
#define LEXER_H_INCLUDED
#include "token.h"
#include <vector>
using namespace std;
class Lexer
{
private:
Token tk = new Token (1, "", 1,0);
vector<Token>::iterator it;
vector<Token> tokensUsed;
Token itrToken; // used for iterator
public:
Token nextToken()
{
if (it!= tokensUsed.end())
{
// we Assigned what is found in the iterator it (of the vector)
// so we get the data found in that pointer
itrToken = &*it;
//Move Iterator forward
it ++;
return &itrToken;
}
else
{
cout << "ERROR" << endl;
}
return nullptr;
}
void getNextToken()
{
cout << "Test" << endl;
string strBuffer = "test";
int row = 0;
int col = 0;
tk = new Token (1,strBuffer,row,col);
}
};
#endif // LEXER_H_INCLUDED
In nextToken() and prevToken() there is no return for the case the if evaluates to false. The return value in that case is not very likely to be something (it could be anything...) that you can then dereference.
If you want to keep the current design you should return nullptr or (NULL if you don't have C++11 support) in that case. Then you need to change any code that uses the result of those functions to check if the pointer is valid before dereferencing it.
You would probably be better changing your design to not involve so much manual pointer manipulation. But to fix up your current version you should change your prevToken and nextToken to be something along the lines of:
Token* nextToken()
{
if (it!= tokensUsed.end())
{
...
return itrToken;
}
else
{
return nullptr;
}
}
Then if tk is the result of calling one of these functions you must not use tk-> or *tk if it is nullptr. Any code wanting to work with the result will need to check first.
So for example you could change you if statement to be:
if (tk && // Make sure tk is not nullptr
tk -> getType() == Token::ttString)
{
...
There are too many problems with your code for me to address them all in this post. The first, and most obvious one is this.
In the main function:
Lexer* l;
l -> getNextToken();
Here, you did not create a Lexer object. You just created an uninitialized pointer to one. Then you called a member function as if it pointed to an object. This is undefined behavior. You then pass this pointer to your Parser class, which continues to treat it as a valid object, resulting in more undefined behavior.
There are many other problems with your code, but most of them have to do with your mishandling of pointers, indicating a lack of understanding of how they work. The best suggestion for you is to stop using them entirely. There is no reason you need to use any pointers whatsoever to do what you are doing. If you can't figure out how to do what you are trying to do without pointers, it is because of a lack of fundamental understanding of the language. You need to read a C++ book, to completion. Here's a list of some good ones.
The Definitive C++ Book Guide and List

C++ Implementing a copy constructor

I am writing some code to implement a deep copy of an object.
Here is my code:
//---------------------------------------------------------------------------
#pragma hdrstop
#include <tchar.h>
#include <string>
#include <iostream>
#include <sstream>
#include <conio.h>
using namespace std;
//---------------------------------------------------------------------------
class Wheel
{
public:
Wheel() : pressure(32)
{
ptrSize = new int(30);
}
Wheel(int s, int p) : pressure(p)
{
ptrSize = new int(s);
}
~Wheel()
{
delete ptrSize;
}
void pump(int amount)
{
pressure += amount;
}
int getSize()
{
return *ptrSize;
}
int getPressure()
{
return pressure;
}
private:
int *ptrSize;
int pressure;
};
class RacingCar
{
public:
RacingCar()
{
speed = 0;
*carWheels = new Wheel[4];
}
RacingCar(int s)
{
speed = s;
}
RacingCar(RacingCar &oldObject)
{
for ( int i = 0; i < sizeof(carWheels)/sizeof(carWheels[0]); ++i)
{
Wheel oldObjectWheel = oldObject.getWheel(i);
carWheels[i]=new Wheel(oldObjectWheel.getSize(),oldObjectWheel.getPressure());
}
}
void Accelerate()
{
speed = speed + 10;
}
Wheel getWheel(int id)
{
return *carWheels[id];
}
void printDetails()
{
cout << carWheels[0];
cout << carWheels[1];
cout << carWheels[2];
cout << carWheels[3];
}
private:
int speed;
Wheel *carWheels[4];
};
#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
RacingCar testCar;
testCar.printDetails();
RacingCar newCar = testCar;
newCar.printDetails();
getch();
return 0;
}
//---------------------------------------------------------------------------
For some reason, my C++ builder crashes after compiling this code. Is there anything above that is not correct that would cause this to crash. There is no compile error, the program just crashes.
The problem is:
Wheel *carWheels[4];
and
*carWheels = new Wheel[4];
this only allocates 4 Wheels for carWheels[0]. Along with
return *carWheels[id];
If id is not 0, this will lead to undefined behavior because, as previously stated, only the first element is a valid pointer.
Besides this, the code is horrible. Avoid raw pointers. There are much better alternatives in C++. Use std::vector or std::array where you'd use a C-array, and smart pointers where you'd use raw ones.
Generally in my experience, if my compiler/tool crashes, I'm probably doing something so wrong that it never even occurred to the compiler writers to check for it.
The best way to track down such things is to comment out code until it works again, then slowly bring stuff back in until you find the offending part.
As a design note, I'd say that if it were me, I'd implement a copy constructor for Wheel as well, rather than having to write a complex deep copy constructor for classes like RacingCar that use it.

Prefix recursion notation in c++

I was looking for recursive solution for evaluating expression in Polish prefix notation, didn't find, but i found pseudo code for that and I wanted to translate it to the C++ but it is hard. I wrote BIG LETTERS where I don't know how to do it. Please correct me I am java guy and for me C++ is big mess, but can't help it.
int preEval(stack<string> stos){
string el = "";
if(stos.empty()){
return 0;
}else if(stos.top() IS VALUE){
string el = stos.top();
stos.pop();
return atoi(el.c_str());
}else if(stos.top() IS OPERATOR){
int x = preEval(stos);
int y = preEval(stos);
return x OPERATOR y;
}
return 0;
}
EDIT
When I have expression like / 10 5 Should stack suppose to have elements(from top) / 10 5, or 5 10 / ? Just asking because if I want it in / 10 5 I have to read string somehow backwards.
I think, a better solution would be to split the work into 2 stages: lexing and parsing.
At the lexing stage, you classify each token to see whether it's an operator (+, -, etc.) or a constant, or maybe a variable. Then you pack the parsed entity into a structure containing the type and additional information.
At the parse stage, which is presented by your code, you work not with strings, but with structures. Looking at the structure, you can easily find out its type. (It can be either a field inside the structure or a structure's type if you choose to build a hierarchy of structures derived from a common base.)
Actually, the logic should be the same in both Java and C++.
If you have functions like these:
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <iostream>
#include <stack>
#include <string>
using std::stack;
using std::string;
using std::cerr;
enum Operator {
operator_none,
operator_plus,
operator_minus
};
Operator tokenOperator(const string &token)
{
if (token=="+") return operator_plus;
if (token=="-") return operator_minus;
return operator_none;
}
int applyOperator(Operator op,int x,int y)
{
switch (op) {
case operator_plus: return x+y;
case operator_minus: return x-y;
case operator_none:
break;
}
assert(false);
return 0;
}
bool isValue(const string &token,int &output_value)
{
char *end = 0;
errno=0;
output_value = strtol(token.c_str(),&end,10);
if (errno!=0) return false;
return *end=='\0';
}
bool isOperator(const string &token,Operator &output_operator)
{
output_operator = tokenOperator(token);
return output_operator!=operator_none;
}
Then preEval can be implemented like this:
int preEval(stack<string> &stos)
{
if (stos.empty()) return 0;
string el = stos.top();
stos.pop();
int value = 0;
Operator op = operator_none;
if (isValue(el,value)) return value;
if (isOperator(el,op)) {
int x = preEval(stos);
int y = preEval(stos);
return applyOperator(op,x,y);
}
return 0;
}
#include <string>
#include <map>
using namespace std;
bool is_value(string s) {
return s.find_first_not_of("0123456789") == string::npos;
}
int do_add(int x, int y) {
return x + y;
}
int do_subtract(int x, int y) {
return x - y;
}
// etc.
typedef int (*binary_op)(int, int); // Give this function pointer type a nice name
map<string, binary_op> ops;
// Somewhere before the preEval() is ever called
ops["+"] = do_add;
ops["-"] = do_subtract; // etc.
binary_op lookup_op(string s) {
map<string, binary_op>::const_iterator it = ops.find(s);
if (it != ops.end()) {
return *it;
} else {
return NULL;
}
}
Now, instead of separately testing whether the token is an operator and later performing that operator, use a single function call to get a pointer to the operator function that needs to be called (if the token is an operator) or NULL otherwise. I.e.:
}else if(stos.top() IS OPERATOR){
int x = preEval(stos);
int y = preEval(stos);
return x OPERATOR y;
}
becomes
} else {
binary_op op = lookup_op(stos.top());
if (binary_op != NULL) {
stos.pop(); // This fixes the bug I mentioned in my top comment
int x = preEval(stos);
int y = preEval(stos);
return op(x, y);
} else {
syntax_error();
}
}

Problems returning vector stack reference

I am working on an application that builds a vector of structs for items in a given directory and returns a reference of the vector for it to be read, I receive the following errors when attempting to compile the example code below:
1. 'class std::vector<indexStruct, std::allocator<indexStruct> >' has no member named 'name'
2. no matching function for call to `std::vector<indexStruct, std::allocator<indexStruct> >::push_back(std::vector<indexStruct, std::allocator<indexStruct> >&)'
exampleApp.cpp
#include "exampleApp.h"
exampleApp::exampleApp()
{
this->makeCatalog();
}
char* findCWD()
{
char* buffer = new char[_MAX_PATH];
return getcwd(buffer, _MAX_PATH);
}
void exampleApp::makeCatalog()
{
char* cwd = this->findCWD();
vector<indexStruct> indexItems;
this->indexDir(cwd, indexItems);
}
void exampleApp:indexDir(char* dirPath, vector<indexStruct>& indexRef)
{
DIR *dirPointer = NULL;
struct dirent *dirItem = NULL;
vector<indexStruct> indexItems;
vector<indexStruct> indexItem;
try
{
if ((dirPointer = opendir(dirPath)) == NULL) throw 1;
while (dirItem = readdir(dirPointer))
{
if (dirItem == NULL) throw 2;
if (dirItem->d_name[0] != '.')
{
indexItem.name = dirItem->d_name;
indexItem.path = dirPath;
indexItems.push_back(indexItem);
indexItem.clear();
}
}
indexRef.swap(indexItems);
closedir(dirPointer);
}
catch(int errorNo)
{
//cout << "Caught Error #" << errorNo;
}
}
exampleApp.h
#ifndef EXAMPLEAPP_H
#define EXAMPLEAPP_H
#include <iostream.h>
#include <dirent.h>
#include <stdlib.h>
#include <vector.h>
using namespace std;
struct indexStruct
{
char* name;
char* path;
};
class exampleApp
{
public:
exampleApp();
private:
char* findCWD();
void makeCatalog();
void indexDir(char* dirPath, vector<indexStruct>& indexRef);
};
#endif
What am I doing wrong here, and is there a better way going about this?
You've made 'indexItem' a vector, you probably just want it to be the type you want to put in 'indexItems'. Also, I'd create the new struct in your loop:
while (dirItem = readdir(dirPointer))
{
if (dirItem == NULL) throw 2;
if (dirItem->d_name[0] != '.')
{
indexStruct indexItem;
indexItem.name = dirItem->d_name;
indexItem.path = dirPath;
indexItems.push_back(indexItem);
}
}
You are defining a vector called indexItem:
vector<indexStruct> indexItem;
This is just an array. So the following lines must be changed to reference a specific element of the vector:
indexItem.name = dirItem->d_name;// should be indexItem[..].name or indexItem.at(..).name
indexItem.path = dirPath; // same as above!