A function that returns a queue? - c++

I'm trying to figure out how queues work in C++ and am getting stuck when dealing with objects. I seem to only be able to get a return address instead of the name of the object (which is what I really want). It's also showing an error when I try to pop the element from the queue. My code is as follows:
Buyer.h file
#ifndef BUYER_H
#define BUYER_H
#include <string>
#include <queue>
#include "Order.h"
#include "Entity.h"
#include "Seller.h"
class Order;
class Seller;
class Buyer : public Entity {
public:
Buyer(const std::string &, const std::string &, double);
virtual ~Buyer() { }; // when step is added make this virtual
void addSeller(Seller *);
std::queue<Seller*> getSellers() const;
void addOrder(Order *);
std::queue<Order*> getOrders() const;
virtual void list() const override;
virtual void step() const override;
private:
std::queue<Order*> orders;
std::queue<Seller*> sellers;
};
#endif
Buyer.cpp file
#include <iostream>
#include <ostream>
#include <stdexcept>
#include <string>
#include <queue>
#include "Buyer.h"
#include "Seller.h"
#include "Order.h"
#include "Entity.h"
using namespace std;
Buyer::Buyer(const std::string &name, const std::string &id, double balance)
: Entity(name, id, balance)
{
// initialize seller and order queue??
} // Constructor
void Buyer::addSeller(Seller *s) {
sellers.push(s);
} // addSeller
std::queue<Seller*> Buyer::getSellers() const {
while(!sellers.empty()) {
return sellers;
} // while
} // getSellers
void Buyer::addOrder(Order *o) {
orders.push(o);
} // addOrder
std::queue<Order*> Buyer::getOrders() const {
while(!orders.empty()) {
return orders;
} // while
} // getOrders
void Buyer::list() const {
Entity::list();
std::cout << "Orders:\nOrder contains:";
std::cout << "\nSellers:\n";
int i = 0;
while(!sellers.empty()) {
std::cout << sellers.front() << "\n";
sellers.pop();
} // while
} //list
void Buyer::step() const {
std::cout << "\nstep enter\n"
<< "step exit\n\n";
} // step
Any help is appreciated! Thank you!

(This isn't a full answer but it is too big to go in a comment)
It's OK to return std::queue<Order *>, and so on. However, you need to be clear on who owns the objects being pointed to; i.e. who is responsible for deleting them.
When you return a std::queue<Order *>, what happens is that the returned queue is a copy of the original one, however all the pointers point to the same object that the original one pointed to . (This is a sort of "shallow copy").
If you then delete anything in the returned queue, you will cause the original queue to malfunction because it will be accessing deleted memory.
As such, this is a fragile design because the caller can easily cause the object to screw up despite the fact that getOrders is a const function.
One "solution" is to make the containers contain shared_ptr<Order> instead of Order *. Then everything happens automatically; the caller can add or delete to his heart's content.
If it is not strictly necessary for the containers to contain pointers, consider using containers of objects: std::queue<Order>. The benefit of this approach is that the default copy and move semantics are all correct.
Another approach to consider is having getOrders() and getSellers() return a const reference, instead of returning a copy of the queue.
NB. In Buyer::getSellers(), and getOrders() if it is empty then you fall off the end of the function without returning, causing undefined behaviour. You need to either return something (what's wrong with returning an empty queue?) or throw an exception.

Related

Struggling with pointers to functions and references

I am working through this problem I found on Git to brush up on some skills. Using friend is prohibited. C++ styling should be used compared to C.
Essentially, I cannot call the identify() function that belongs to the Brain member variable in my Human class. It just will not let me access it. If you can code this up, and explain where I am going wrong, that would be great.
Create a Brain class, with whatever you think befits a brain. It will have an Identify() function that returns a string containing the brain's address in memory, in hex format, prefixed by 0x.
Then, make a Human class, that has a constant Brain attribute with the same lifetime. It has an identify() function, that just calls the identity() function of its Brain and returns its result.
Now, make it so this code compiles and displays two identical addresses:
int main(){
Human bob;
std::cout << bob.identify() << "\n";
std::cout << bob.getBrain().identify() << "\n";
}
Here is what I have so far:
#pragma once
#include "Brain.h"
class Human
{
const Brain humanBrain;
public:
Human();
std::string identify();
};
#include "Human.h"
#include <iostream>
#include <string>
#include <sstream>
Human::Human()
{
this->humanBrain = new Brain;
}
std::string Human::identify()
{
Brain b = this->humanBrain.identify(); // This is essentially what I am trying to call--and I can't access it.
const Brain * ptr = humanBrain;
std::ostringstream test;
test << ptr;
return test.str();
}
#pragma once
#include <string>
#include <iostream>
class Brain
{
int age;
std::string gender;
void* ptr;
public:
Brain();
//std::string getBrain();
const std::string identify();
void setPtr(void* p);
};
#include "Brain.h"
#include <iostream>
#include <sstream>
Brain::Brain()
{
age = 10;
gender = "male";
}
const std::string Brain::identify()
{
//const Brain* bPtr = &this;
const Brain* bPtr = this;
ptr = this;
std::ostringstream test;
test << &bPtr;
std::string output = "Brain Identify: 0x" + test.str();
return output;
}
Your Human::humanBrain member is declared as type const Brain, which is correct per the instructions, however your Brain::identify() method is not qualified as const, so you can't call it on any const Brain object. This is the root of the problem that you are having trouble with.
In addition, there are many other problems with your code, as well:
Human::humanBrain is not a pointer, so using new to construct it is wrong. And, you don't need a pointer to get the address of a variable anyway. Nor do you actually need a pointer to the member at all in this project.
Human lacks a getBrain() method, so bob.getBrain() in main() will not compile, per the instructions.
Human::identify() is calling humanBrain.identify(), which returns a std::string as it should, but is then assigning that string to a local Brain variable, which is wrong (not to mention, you are not even using that variable for anything afterwards). The instructions clearly state that Human::identity() should simply call Brain::identify() and return its result, but you are not doing that.
Brain::identify() is printing the address of its local variable bPtr rather than printing the address of the Brain object that identify() is begin called on, per the instructions.
With all of that said, try something more like this instead:
Human.h
#pragma once
#include "Brain.h"
#include <string>
class Human
{
const Brain humanBrain;
public:
Human() = default;
std::string identify() const;
const Brain& getBrain() const;
};
Human.cpp
#include "Human.h"
std::string Human::identify() const
{
return humanBrain.identity();
}
const Brain& Human::getBrain() const
{
return humanBrain;
}
Brain.h
#pragma once
#include <string>
class Brain
{
int age;
std::string gender;
public:
Brain();
std::string identify() const;
};
Brain.cpp
#include "Brain.h"
#include <sstream>
Brain::Brain()
{
age = 10;
gender = "male";
}
std::string Brain::identify() const
{
std::ostringstream test;
test << "Brain Identify: 0x" << this;
return test.str();
}

"Attempting to reference a deleted function" after adding QMutex to class

I am building an application with Qt5. My program builds and runs fine, but there is a collision between two threads accessing a data structure. I have a QList of CanMessage objects, and I want to protect some data inside of it using a QMutex. However, as soon as I add the QMutex to my class definition, I get errors:
QList.h: `error: C2280:
'CanMessage::CanMessage(const CanMessage &)': attempting to reference a deleted function`.
Here is my canmessage.h file:
#ifndef CANMESSAGE_H
#define CANMESSAGE_H
#include <QObject>
#include <QMutex>
#include "cansignal.h"
class CanMessage
{
public:
CanMessage();
/* snip - public function prototypes */
private:
/* snip - private prototypes and data */
QMutex m_messageMutex;
};
#endif // CANMESSAGE_H
And cansignal.h:
#ifndef CANSIGNAL_H
#define CANSIGNAL_H
#include <QObject>
#include <QDebug>
#include <QByteArray>
class CanSignal
{
public:
CanSignal();
CanSignal(QString &signalName, quint8 &signalLength, quint8 &signalStartBit,
float &offset, float &factor, bool &isBigEndian, bool &isFloat, bool &isSigned)
{
this->m_name = signalName;
this->m_length = signalLength;
this->m_startBit = signalStartBit;
this->m_offset = offset;
this->m_factor = factor;
this->m_isBigEndian = isBigEndian;
this->m_isFloat = isFloat;
this->m_isSigned = isSigned;
}
bool setName(QString &signalName);
bool setBitLength(quint8 &length);
bool setStartBit(quint8 &startBit);
bool setOffset(float &offset);
bool setFactor(float &factor);
bool setEndianess(bool &isBigEndian);
bool setIsFloat(bool &isFloat);
bool setIsSigned(bool &isSigned);
void setValid();
void setInvalid();
void setEngineeringData(float data);
QString getName();
quint8 getBitLength();
quint8 getStartBit();
float getOffset();
float getFactor();
float getData();
bool isBigEndian();
bool isFloat();
bool isSigned();
bool getSignalValidity();
private:
QString m_name;
quint8 m_length;
quint8 m_startBit;
float m_offset;
float m_factor;
float m_data_float = 0;
bool m_isBigEndian;
bool m_isFloat;
bool m_isSigned;
// Set After everything in signal is filled
bool m_isSignalValid = false;
};
#endif // CANSIGNAL_H
CanMessage::CanMessage(const CanMessage &)
is the copy constructor, obviously being used to place an item into the list. That's not going to work since QMutex is not actually copyable.
How you solve it depends on a number of things. Perhaps the easiest method would be to modify CanMessage so that it has a dynamic mutex (created in the constructor, of course).
Then have a copy constructor for it that first locks the source object mutex then dynamically allocates a new mutex in the target object.
That way, you can guarantee the old object will be "clean" when copying (because you have its mutex) and there'll be no "trying to copy an uncopyable member" problem since the mutex itself is not copied. See footnote (a) for details.
The following code, which is a complete simple snippet showing the problem, compiles okay provided you leave the QMutex m_mutex; line commented out:
#include <QList>
#include <QMutex>
#include <iostream>
class Xyzzy {
private:
int m_xyzzy;
//QMutex m_mutex;
public:
Xyzzy() : m_xyzzy(0) {};
Xyzzy(int val) : m_xyzzy(val) {};
};
int main() {
QList<Xyzzy> myList;
Xyzzy plugh;
myList.push_back(plugh);
return 0;
}
Once you un-comment that line, the compiler rightly complains:
error: use of deleted function 'Xyzzy::Xyzzy(const Xyzzy&)'
(a) In terms of fixing the problem, you could do something like:
#include <QList>
#include <QMutex>
#include <iostream>
class Xyzzy {
private:
int m_xyzzy;
QMutex *m_mutex; // Now a pointer
public:
Xyzzy() : m_xyzzy(0) {
m_mutex = new QMutex(); // Need to create in constructor.
std::cout << "constructor " << m_mutex << '\n';
};
~Xyzzy() {
std::cout << "destructor " << m_mutex << '\n';
delete m_mutex; // Need to delete in destructor.
}
Xyzzy(const Xyzzy &old) {
old.m_mutex->lock();
m_mutex = new QMutex(); // Need to make new one here.
std::cout << "copy constructor from " << old.m_mutex
<< " to " << m_mutex << '\n';
old.m_mutex->unlock();
}
};
int main() {
QList<Xyzzy> myList;
Xyzzy plugh;
myList.push_back(plugh);
return 0;
}
That one works properly, as per the following test run:
constructor 0x21c9e50
copy constructor from 0x21c9e50 to 0x2fff2f0
destructor 0x21c9e50
destructor 0x2fff2f0
In real code, I'd probably opt for smart pointers rather than raw new/delete calls but this is only meant to illustrate the concept. In addition, you'd need to handle all other possibilities which create a new object from an existing one as per the rule of three/five/whatever-comes-next, currently (from memory) limited to the copy assignment member Xyzzy &operator=(const Xyzzy &old).

C++ Why didn't the default copy work? [duplicate]

This question already has answers here:
Why does the C++ map type argument require an empty constructor when using []?
(6 answers)
Closed 5 years ago.
I've done a lot of Googling and can't seem to figure out what's going on. I'm teaching myself C++ (I'm more familiar with Java).
I have Item Class objects that are being stored in an Inventory Class map, not as pointers. I want to retrieve one of the items from the Inventory in a function, assign it to a temp variable while I delete it from the Inventory map, and then return the object itself so something else can use it. When I originally tried using the code within my function it was returning the error (followed by the stack trace of c++ library stuff):
no matching constructor for initialization of 'Item'
::new ((void*)__p) _Tp();
I tried creating a copy constructor, but to no avail. Eventually, it worked by including an empty constructor ( Item(); ) in my header file and defining it in my cpp file ( Item::Item() {} ).
I would just like to understand why this was necessary so I can recognize it in the future to know what I'm doing.
EDIT: Upon further inspection of the error stack trace, it turned out the actual problem with with the Inventory::addItem function. When assigning an object to a map using operator[], the map first instantiates the value type to the key using the default constructor before making the assignment. No default constructor was available, so the error was returned.
It was fixed by changing the line to map.insert({key, value})
Here are the important parts of the two class files:
//item.h
#include <string>
using namespace std;
class Item {
private:
string name;
int type;
int levelReq;
public:
Item(string name, int type, int levelReq);
Item();
string getName() {return name;}
int getType() {return type;}
friend ostream &operator<<(ostream &out, const Item &item);
};
---------------------------------------------------------------
//item.cpp
#include <string>
#include "item.h"
using namespace std;
Item::Item(string n, int t, int l) : name(n), type(t), levelReq(l) {}
Item::Item() {}
ostream &operator<<(ostream &out, const Item &item) {
return out << item.name;
}
---------------------------------------------------------------
//inventory.h
#include <map>
#include "item.h"
class Inventory {
private:
map <int, Item> inventory;
int size;
bool full;
int nextFree;
void findNextFree();
public:
Inventory();
bool isFull() {return full;}
void addItem(Item item);
Item getItem(int slot);
void showInv();
};
---------------------------------------------------------------
//inventory.cpp
#include <iostream>
#include <string>
#include "inventory.h"
#include "item.h"
using namespace std;
Inventory::Inventory() {
full = false;
nextFree = 1;
size = 28;
}
void Inventory::addItem(Item item) {
if (!full) {
inventory[nextFree] = item;
findNextFree();
}
else {
cout << "Your inventory is full (Inv::addItem)";
}
}
Item Inventory::getItem(int slot) {
Item item = inventory.at(slot);
inventory.erase(slot);
full = false;
if (nextFree > slot) {
nextFree = slot;
}
return item;
}
void Inventory::findNextFree() {
nextFree++;
if (nextFree == size + 1) {
full = true;
}
else if (inventory.count(nextFree)) {
findNextFree();
}
}
I think the issue rose because you declared a constructor for your item class.
C++ will automatically generate the necessary constructors if you don't provide any custom constructors.
The necessary constructors are the default, copy and move constructors.
The moment you provide one, the default constructors won't be generated and you have this issue. This principle will also apply to structs.
Check the reference to see for yourself:
http://en.cppreference.com/w/cpp/language/default_constructor
http://en.cppreference.com/w/cpp/language/copy_constructor
http://en.cppreference.com/w/cpp/language/move_constructor
Hope this answers your question.

C++11, shared_ptr.reset() and cyclic references

I have a question about the behaviour of shared_ptr.reset().
In this scenario I have a cyclic reference with the following classes. I have a book and an owner, which both have std::shared_ptrs to each other, creating a cyclic reference.
Book.h
#pragma once
class Owner;
class Book
{
public:
Book(std::string title);
~Book();
void OutputDetails();
void SetOwner(std::shared_ptr<Owner> owner);
void OutputOwnerInformation();
private:
std::string m_title;
std::shared_ptr<Owner> m_owner; // Book hangs onto the owner and creates a circular dependency
};
Book.cpp
#include "stdafx.h"
#include <iostream>
#include "Book.h"
#include "Owner.h"
Book::Book(std::string title) : m_title(title) {}
Book::~Book() {
std::cout << "Book Destroyed" << std::endl;
}
void Book::SetOwner(std::shared_ptr<Owner> owner) {
m_owner = owner; // strong reference
}
void Book::OutputOwnerInformation() {
std::cout << "Owner is: " << m_owner->GetName() << std::endl;
}
void Book::OutputOwnerInformation() {
std::cout << "Owner is: " << m_owner->GetName() << std::endl;
}
Owner.h
#pragma once
class Book; // To avoid circular #includes
class Owner
{
public:
Owner(std::string name, std::shared_ptr<Book> book);
~Owner();
void OutputDetails();
std::string GetName();
private:
std::string m_name;
std::shared_ptr<Book> m_book; // Owner hangs onto the book
};
Owner.cpp
#include "stdafx.h"
#include "Owner.h"
#include "Book.h"
Owner::Owner(std::string name, std::shared_ptr<Book> book) : m_name(name), m_book(book) {}
Owner::~Owner() {
std::cout << "Owner Destroyed" << std::endl;
}
void Owner::OutputDetails() {
std::cout << m_name << " owns " << std::endl;
m_book->OutputDetails();
}
std::string Owner::GetName() {
return m_name;
}
Here is the main.cpp. In this case, book and owner have strong references to each other and will memory leak once _tmain exits its scope. The destructors for both book and owner are not called when I insert breakpoints in the respective destructors.
main.cpp
#include "stdafx.h"
#include <memory>
#include "Book.h"
#include "Owner.h"
int _tmain(int, _TCHAR*)
{
{
std::shared_ptr<Book> book = std::shared_ptr<Book>(new Book("Moby Dick"));
std::shared_ptr<Owner> owner = std::shared_ptr<Owner>(new Owner("George Heriot", book));
// Introduced a circular dependency so
// neither gets deleted
book->SetOwner(owner);
owner->OutputDetails();
book->OutputOwnerInformation();
}
return 0;
}
I wanted to see if I could reset() the pointers such that the destructor was called and to break the cyclic dependency. According to my understanding of shared_ptr.reset(), the object should become empty.
http://www.cplusplus.com/reference/memory/shared_ptr/reset/
However, my break points in both destructors are not being hit. My assumption would be that because I have reset both book and owner, the reference count would drop to 0 for both and they would be destroyed when _tmain returns.
main2.cpp
#include "stdafx.h"
#include <memory>
#include "Book.h"
#include "Owner.h"
int _tmain(int, _TCHAR*)
{
{
std::shared_ptr<Book> book = std::shared_ptr<Book>(new Book("Moby Dick"));
std::shared_ptr<Owner> owner = std::shared_ptr<Owner>(new Owner("George Heriot", book));
// Introduced a circular dependency so
// neither gets deleted
book->SetOwner(owner);
owner->OutputDetails();
book->OutputOwnerInformation();
owner.reset();
book.reset();
}
return 0;
}
I understand that this is already horrible code and I could use a weak_ptr to remove the cyclic dependency but I am just curious why reset() does not break this dependency.
Try printing owner.use_count() and book.use_count() before resetting them. You'll see the use counts are 2. The reset calls will make owner and book decrement their counts by 1, but there are still other shared_ptr objects that share ownership with them and which you don't reset, so the reference counts don't reach zero.
If you think about it you should realise that of course reset() can't break cycles, because the equivalent of reset() happens in the shared_ptr destructor anyway. If the destructor could break cycles like that then there would be no problem creating cycles in the first place.

Function calls with class members?

Before I present the code which is found at the bottom of this post I would like to talk about the issue and the fix's that I do not desire. Okay basically I've created a GUI from scratch sort of and one requirement I wanted for this was allow components to have their own click executions so if i click a button or tab etc.. It would call Component->Execute(); Well normally you would do something like a switch statement of ids and if that components ID equaled n number then it would perform this action. Well that seemed kinda dumb to me and I thought there has to be a better way. I eventually tried to incorporate a feature in JAVA where you would do like Component.AddActionListener(new ActionListener( public void execute(ActionEvent ae) { })); or something like that and I thought that this feature has to be possible in C++. I eventually came across storing void functions into a variable in which could be executed at any time and modified at any time. However I hadn't noticed an issue and that was this only worked with static functions. So below you'll see my problem. I've patched the problem by using a pointer to SomeClass however this would mean having an individual function call for every class type is there no way to store a function callback to a non-static class member without doing the below strategy? and instead doing a strategy like the commented out code?
//Main.cpp
#include <iostream> //system requires this.
#include "SomeClass.h"
void DoSomething1(void)
{
std::cout << "We Called Static DoSomething1\n";
}
void DoSomething2(void)
{
std::cout << "We Called Static DoSomething2\n";
}
int main()
{
void (*function_call2)(SomeClass*);
void (*function_call)() = DoSomething1; //This works No Problems!
function_call(); //Will Call the DoSomething1(void);
function_call = DoSomething2; //This works No Problems!
function_call(); //Will Call the DoSomething2(void);
SomeClass *some = new SomeClass(); //Create a SomeClass pointer;
function_call = SomeClass::DoSomething3; //Static SomeClass::DoSomething3();
function_call(); //Will Call the SomeClass::DoSomething3(void);
//function_call = some->DoSomething4; //Non-Static SomeClass::DoSomething4 gives an error.
//function_call(); //Not used because of error above.
function_call2 = SomeClass::DoSomething5; //Store the SomeClass::DoSomething(SomeClass* some);
function_call2(some); //Call out SomeClass::DoSomething5 which calls on SomeClass::DoSomething4's non static member.
system("pause");
return 0;
}
//SomeClass.hpp
#pragma once
#include <iostream>
class SomeClass
{
public:
SomeClass();
~SomeClass();
public:
static void DoSomething3(void);
void DoSomething4(void);
static void DoSomething5(SomeClass* some);
};
//SomeClass.cpp
#include "SomeClass.h"
SomeClass::SomeClass(void)
{
}
SomeClass::~SomeClass(void)
{
}
void SomeClass::DoSomething3(void)
{
std::cout << "We Called Static DoSomething3\n";
}
void SomeClass::DoSomething4(void)
{
std::cout << "We Called Non-Static DoSomething4\n";
}
void SomeClass::DoSomething5(SomeClass *some)
{
some->DoSomething4();
}
Secondary Fix for what I'll do not an exact answer I wanted but it meets my needs for now along with allowing additional features which would have become overly complicate had this not existed.
//Component.hpp
#pragma once
#include <iostream>
#include <windows.h>
#include <d3dx9.h>
#include <d3d9.h>
#include "Constants.hpp"
#include "ScreenState.hpp"
#include "ComponentType.hpp"
using namespace std;
class Component
{
static void EMPTY(void) { }
static void EMPTY(int i) { }
public:
Component(void)
{
callback = EMPTY;
callback2 = EMPTY;
callback_id = -1;
}
Component* SetFunction(void (*callback)())
{
this->callback = callback;
return this;
}
Component* SetFunction(void (*callback2)(int), int id)
{
this->callback_id = id;
this->callback2 = callback2;
return this;
}
void execute(void)
{
callback();
callback2(callback_id);
}
}
The syntax for pointers-to-member-functions is as follows:
struct Foo
{
void bar(int, int);
void zip(int, int);
};
Foo x;
void (Foo::*p)(int, int) = &Foo::bar; // pointer
(x.*p)(1, 2); // invocation
p = &Foo::zip;
(x.*p)(3, 4); // invocation
Mind the additional parentheses in the function invocation, which is needed to get the correct operator precedence. The member-dereference operator is .* (and there's also ->* from an instance pointer).