How can i prevent dereferencing using cpp - c++

I am having following code in my cpp file,too many dereferencing are getting here, can anybody suggest me what can i do to prevent this .
aObj* bObj = NULL;
bObj = getG()->getO(bObjId);
AbstractionType eAT= bObj->GetAT();
long nObjType = bObj->GetOT()

One option is to create a reference to the object the pointer tracks:
aObj* p_bObj = getG()->getO(bObjId);
aObj& bObj = *p_bObj; // <-- once for convenience
AbstractionType eAT= bObj.GetAT(); // use .-notation however-many times
long nObjType = bObj.GetOT();
If you need the pointer (p_bObj above) to delete the object later, consider storing it in a std::unique_ptr<> or std::shared_ptr<> instead of an aObj* - that way you can be sure of delete-ion even if the program "tries to circumvent" the delete due to an exception, return, break, goto etc..
If you don't also need a pointer at all then you could create the reference directly:
aObj& bObj = *(getG()->getO(bObjId));

Related

Qt - Function returns pointer, that gets deleted

I have a function which returns a pointer to a local variable, which I used new on to allocate to the heap. However, as soon as the return pointer is used, it causes a seg fault.
IConnectionDesc *ConnectionDialog::uiToConnection(IConnectionDesc *conDesc)
{
_lrtrace();
IConnectionDesc *result = nullptr;
if (conDesc)
result = conDesc;
else
result = new ConnectionDesc();
result->setName(ConnectionDesc::connectionNameForReport(ui->leConnectionName->text()));
result->setAutoconnect(ui->cbAutoConnect->isChecked());
result->setKeepDBCredentials(!ui->cbbKeepCredentials->isChecked());
if (ui->tabWidget->currentIndex() == 0)
{
ConnectionDesc *lrresult = new ConnectionDesc();
lrresult->createFrom(result);
lrresult->setHost(ui->leServerName->text());
lrresult->setPort(ui->lePort->text());
lrresult->setDriver(ui->cbbDrivers->currentText());
lrresult->setUserName(ui->leUserName->text());
lrresult->setPassword(ui->lePassword->text());
lrresult->setDatabaseName(ui->leDataBase->text());
_lrendtrace();
return lrresult;
}
else
{
HBOConnectionDesc *hboresult = new HBOConnectionDesc();
hboresult->createFrom(result);
hboresult->setApplication(ui->cbbhboapplication->currentText());
hboresult->setService(ui->cbbhboservice->currentText());
_lrendtrace();
return hboresult;
}
}
IConnectionDesc is an interface, which inherits from QObject, ConnectionDesc and HBOConnectionDesc both inherit from IConnectionDesc. createFrom just copies the shared properties into the instance. This kind of issue occurs in bigger functions, where a lot more is shared too, hence why I'd prefer to keep the single instances of result->setName(
I've tried multiple different versions of this, but either Qt's Q_DISABLE_COPY or a Segementation fault cause an issue. I have no idea what else to do.
I cannot make the function simply edit the provided conDesc, because its optional, and could be a null pointer itself.

how to find the ways of handling pointer difference between ptr and ->

what is the difference of pointers between and which is better in terms of memory management
void Loo(){
Song* pSong = new Song(…);
//…
string s = pSong->duration;
}
and
void Hoo(){
unique_ptr<Song> song2(new Song(…));
//…
string s = song2->duration;
}
In the first case you need to call delete yourself and make sure it happens on all program control paths.
That is easier said than done. It's tempting to write delete pSong; just before the closing brace of the function and be done with it. But what happens, say, if string s = song2->duration throws an exception? (Yes it's possible; for example if song2->duration is a type that has a conversion operator defined so it can be assigned to a string.)
With std::unique_ptr, delete will be called for you when it goes out of scope.
Although in this particular case Song song(...); may be more appropriate.

Get object from pointer C++

I have a vector of objects (DimensionItem) and I want to push another item to the vector. I only have a pointer to the object I wish to push. How can I get the object from the pointer.
(New to pointers, very possible I'm am fundamentally misunderstanding something)
DimensionItem *selected_Item = dynamic_cast<DimensionItem*>(g_items[i]); //g_items is a list of items taken from my scene
vector<DimensionItem> DimItems;
DimItems.push_back(selected_Item);
The error message is:
no matching function for call to 'std::vector::push_back(DimensionItem*&)'
You probably want:
DimensionItem& selected_Item = dynamic_cast<DimensionItem&>(*g_items[i]); // Throws if g_items[i] is not DimensionItem.
vector<DimensionItem> DimItems;
DimItems.push_back(selected_Item); // Stores a copy of selected_Item.
dynamic_cast<DimensionItem*>(g_items[i]) returns a null pointer if g_items[i] is not a DimensionItem, so the code would need to check the pointer for null before dereferencing it.
Whereas dynamic_cast<DimensionItem&>(*g_items[i]) throws an exception in that case.

Pointers and memory allocation in C++

I recently started with C++ and i'm not entirely sure I grasp the concept of pointers and their connection to arrays. I have two classes, Term and Polynom. I have a main loop which allows the user to enter 2 numbers. Those numbers is then added to the "Term" object and that object is then added to the "Polynom" object. Everytime the loop is executed a new "Term" object is created.
//These lines are executed until the user is done entering numbers
potens = new Term;
potens->sattPotens(kinput, ninput);//Add values to "Term object"
poly.addTerm(potens);//Add "Term" object to "Polynom" object
A "Polynom" object is only created once in the program. In the "Polynom" class I use a "Term" pointer to store all the "Term" objects that is added to the "Polynom" object. The "Term" pointer in the "Polynom" class is initiated once in the "Polynom" constructor.
void Polynom::addTerm(Term *t){
*(term+antal_termer) = *t;//This is were the program crashes
antal_termer++;
}
I know I could use a vector instead of a pointer to store the "Term" objects but i'm trying to learn how pointers work. I am also unsure when I'm supposed to delete the objects created in the main loop. Since every time the loop is executed I create a new "Term" object but I never delete them.
EDIT: I used to allocate the "Term" object in the "Polynom" class this way: term = new Term[]; I then changed it to term = new Term[10]; but I still crashes when I execute term[antal_termer] = *t;
*(term+antal_termer) = *t;//This is were the program crashes
antal_termer++;
This crashes because you probably haven't allocated enough memory. Your best choice is to use a std::vector instead of a dynamic array.
Is term allocated term = new Term; or term = new Term[sz];?
If it's the first, you can only store one object, and term+antal_termer goes beyond that. If it's the second, you run into problems if antal_termer >= sz.
The std::vector option gives you automatic management:
std::vector<Term> terms;
Term potens; //why use new?
terms.push_back(potens);
Note that I'm using objects, not pointers. For pointers, it'd be
std::vector<Term*> terms;
Term* potens = new Term;
terms.push_back(potens);
But note that you have to delete the memory when you're done with it.
Pasting in outcome from comments.
antal_termer was not initialised in the constructor, resulting in invalid memory access here:
*(term+antal_termer) = *t;
As the code is copying t, via assignment, you can delete potens; after the call to addTerm(). The code must prevent going beyond the end of the term array in addTerm(), otherwise another invalid memory access will occur:
void Polynom::addTerm(Term *t){
if (antal_termer < 10) // Use constant instead of literal 10
{
*(term+antal_termer) = *t;
antal_termer++;
}
}

Calling new multiple times within same for loop

Here is a quick snippet of my code to parse PDB files for molecular dynamics simulations:
Structure *s = new Structure(pdb_filename);
Chain *c = new Chain();
while( ... read file ... ) {
if ( ... new chain ... ) {
Chain *c = new Chain();
s->add_child(c); // Add reference to a vector to
// save the Chain for later
}
}
When the containing function is called, the code acts as normal and gives brand new Structure and Chain objects as in the first two lines of the snippet.
When the criteria for a new chain is met again while looping over the file, the code returns the same Chain pointer to the object as before.
Will g++ give the same pointer over and over? Is there any way to get around this?
If I add the c pointer to the 's' children vector, I assume calling delete c will cause even larger headaches?
Structure *s = new Structure(pdb_filename);
Chain *c = new Chain();
You just defined c here
while( ... read file ... ) {
if ( ... new chain ... ) {
Chain *c = new Chain();
You just defined c here again shadowing the other one.
When the criteria for a new chain is met again while looping over the
file, the code returns the same Chain pointer to the object as before.
Now which one of the two you're looking at?
I think you can see the problem already.
the code returns the same Chain pointer to the object as before
That is hard to believe.
Will g++ give the same pointer over and over?
No. Each time you call new Chain it's a different Chain. It's a different pointer, pointing to different memory (that's why it's new). It's also shadowing the c before the while.
new Chain() should give a different pointer each time
I think I may have an inkling what your problem is--
The c within your loop does not refer to the same variable as the c outside your loop. The c outside your loop will retain its same value all the way through.