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.
Related
I don't know why it doesn't work. I tried to do it with push_back and it doesn't work either.
When I try to debug it I get error:
GeneticAlgorithm(8942,0x7fffc40183c0) malloc: * mach_vm_map(size=1059546636242944) failed (error code=3)
* error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc
I also tried to resize vectorOfIndividuals but then I get BAD_ACCESS ERROR
Population children(population);
population.getVectorOfIndividuals().insert(population.getVectorOfIndividuals().begin(),children.getVectorOfIndividuals().begin(),children.getVectorOfIndividuals().end());
Population copying constructor:
Population::Population(const Population &populationToSave){
vectorOfIndividuals = populationToSave.vectorOfIndividuals;
bestFitnessScore = populationToSave.bestFitnessScore;
}
Getter:
vector<Individual> Population::getVectorOfIndividuals(){
return vectorOfIndividuals;
}
I would be very grateful for your help.
Your getter must return a reference, not a copy:
vector<Individual>& Population::getVectorOfIndividuals()
{
return vectorOfIndividuals;
}
Else, when you do:
population.getVectorOfIndividuals().insert(population.getVectorOfIndividuals().begin(),children.getVectorOfIndividuals().begin(),children.getVectorOfIndividuals().end());
You mix different objects together (you insert to one, at the beginning of another...as every call to population.getVectorOfIndividuals() returns a different vector<Individual> object: it's like doing vectorA.insert(vectorB.begin(),vectorC.begin(),vectorC.end()), which is not valid...vectorA and vectorB must be the same object).
Your method:
vector<Individual> Population::getVectorOfIndividuals()
returns vector instance by value, which means every time you call this method a new copy is created. So first of all you pass begin() of another vector for which you call insert and begin() and end() of children also iterators for 2 different containers. Also result of insert would be dropped even if you pass parameters properly. Most probably you want that method to return vector<Individual> by reference.
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));
I have a class TypeData and want to store objects of that type in a QMap then I want to get a specific object out of the map and call a memberfunction of this object.
But when I try to do that i get the following error message:
error C2662: 'TypeData::write': cannot convert 'this' pointer from 'const TypeData' to 'TypeData &'
here are the relevant code snippets:
QMap<QString, TypeData> typeDataList;
typeDataList.insert(currentID, temp);
typeDataList.value(currentID).write();
Can anyone tell what I', doing wrong here? And how I could fix this?
QMap::value returns a const T, i.e. a both a copy of the element in the map, and a non-modifyable one. Your write() method is probably not const, thus calling write() on the const T is not allowed. If value returned just T, it would work, but any changes write() does to the temporary object would be lost right away. (As the copy is destroyed right after).
So you can either make write() const if it doesn't modify the TypeData.
That's preferable, if possible.
Alternatively you can do:
typeDataList[currentID].write() // modifies the object in the map but also will insert a TypeData() if there is no entry for key currentID yet.
or, more verbose but without inserting a new element if none is found:
QMap<QString,TypeData>::Iterator it = typeDataList.find(currentID);
if ( it != typeDataList.constEnd() ) {
it->write();
} else {
// no typedata found for currentID
}
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++;
}
}
(Disclaimer: I have removed the Qt tag in case the problem is in my syntax / understanding of the references involved here)
I have a foreach loop with an object Member. When I enumerate through the list and try to access a member field, the debugger stops and I get a message:
Stopped: 'signal-received' -
The assert failure is:
inline QString::QString(const QString &other) : d(other.d)
{ Q_ASSERT(&other != this); d->ref.ref(); }
I have checked if the member is NULL, and it isn't. I have tried re-working the code, but I keep failing on this simple call.
Some thing's I missed out. MemberList is a singleton (definitely initialized and returns a valid pointer) that is created as the application launches and populates the MemberList with Members from a file. When this is created, there are definitely values, as I print them to qDebug(). This page is literally the next page. I am unsure as to how the List items can be destroyed.
The code is as follows:
int i = 0;
QList<Member*> members = ml->getMembers();
foreach (Member* mem, members)
{
QString memID = mem->getMemberID(); // Crash happens here
QListWidgetItem *lstItem = new QListWidgetItem(memID, lsvMembers);
lsvMembers->insertItem(i, lstItem);
i++;
}
The Member classes get is as follows:
QString getMemberID() const;
and the actual function is:
QString Member::getMemberID() const
{
return MemberID;
}
The ml variable is received as follows:
QList<Member*> MemberList::getMembers()
{
return MemberList::getInstance()->memberList;
}
Where memberList is a private variable.
Final answer:
I decided to rework the singleton completely and found that I was not instantiating a new Member, rather reusing the previous object over and over. This caused the double reference. S'pose thats pointers for you. Special thanks to Troubadour for the effort!
If mem is not null it could still be the case that the pointer is dangling i.e. the Member it was pointing to has been deleted.
If Member inherits from QObject then you could temporarily change your QList<Member*> that is stored in ml (assuming that's what's stored in ml) into a QList< QPointer<Member> >. If you then get a null QPointer in the list after calling getMembers or at any point during the loop then the object must have been destroyed at some point.
Edit
As regards the singleton, are you sure it's initiliased properly? In other words does MemberList::getInstance() return a valid pointer or just a random uninitialised one?
Edit2
Since we've exhausted most possibilities I guess it must be in the singleton somewhere. All I can suggest is to keep querying the first item in the list to find out exactly where it goes bad.