I have a constructor inside a method that I want to have access at all time
//ItemEditor.cpp
#include "ItemContainer.h"
void ItemEditor::CreateItem() {
ItemContainer* wornItems = new ItemContainer();
}
inside of my driver I call my method createItem();
//driver
int main(){
ItemEditor* createItem = new ItemEditor();
createItem->CreateItem();
}
afterwards I want to have access to backpack outside of the createItem
How can I accomplish that?
Make the item container a member variable so its scope is the life time of the object.
There is no reason to use dynamic allocation, so just use an instance of the ItemContainer instead of a pointer.
#include <iostream>
class ItemContainer {
int item = 0;
public:
void addItem(int i) {
item = i;
}
int getItem() {
return item;
}
};
class ItemEditor {
public:
ItemEditor() {
}
void createEditor() {
wornItems.addItem(3);
}
ItemContainer wornItems;
};
int main() {
ItemEditor editor;
int item = editor.wornItems.getItem(); //or some method
std::cout << item << std::endl;
editor.createEditor();
item = editor.wornItems.getItem(); //or some method
std::cout << item;
return 0;
}
You can also make the container private and use public methods to access its contents. You can see an example here
By backpack I assume whatever is returned by
createItem->CreateItem();
Why not just store it in a pointer since you used the new to allocate the object in a heap?
ItemContainer* ItemEditor::CreateItem() {
return new ItemContainer();
}
Main file:
int main(){
ItemEditor* createItem = new ItemEditor();
ItemContainer* backpack = createItem->CreateItem();
}
Also I want to suggest it is a better practice to provide a move semantic for ItemContainer and get rid of pointers. That way you are relying on RAII and stack for object destruction, less risk of memory-leak. Related article:
http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
Here is a full compiling code:
//Header.h
#include <iostream>
class ItemContainer{
public:
void sayHello(){
std::cout << "HulloWorld!\n";
}
};
class ItemEditor{
public:
ItemEditor(){};
ItemContainer* ItemEditor::CreateItem(){
return new ItemContainer();
}
};
MainFile:
//main
#include "Header.h"
int main()
{
ItemEditor* createItem = new ItemEditor();
ItemContainer* backpack = createItem->CreateItem();
backpack->sayHello();
}
Related
I'm working on a call center call queue simulation model. I've created a vector of caller objects and assigned them exponential distributed random inter-arrival times, then assigned calculated arrival times in the call center class. I would like to then copy each caller object into a vector priority queue, however I keep receiving this error when i push a caller vector object into the queue:
Error C2280 'Caller::Caller(const Caller &)': attempting to reference a deleted function
I've been trying to fix it for a while now and cannot seem to figure out what is causing the issue or how to fix it. I'm trying to push an already created object, so I'm not sure why I would get a reference to a deleted function. Any help would be appreciated.
My Caller.h file
#pragma once
#include <random>
#include <time.h>
using namespace std;
class Caller
{
private:
bool isPaid;
int priority;
double arrivalTime;
double iarrivalTime;
default_random_engine e1;
random_device rd1;
public:
Caller();
Caller(bool p);
void setPriority();
int getPriority();
void generateInterArrivalTime();
double getInterArrivalTime();
void setArrivalTime(double t);
double getArrivalTime();
};
My Caller.Cpp file
#include "Caller.h"
Caller::Caller() : isPaid(false), priority(0), iarrivalTime(0), arrivalTime(0)
{
}
Caller::Caller(bool p): isPaid(false), priority(0), iarrivalTime(0)
{
isPaid = p;
}
void Caller::setPriority()
{
if (isPaid == true)
{
priority = 1;
}
else(priority = 0);
}
int Caller::getPriority()
{
return priority;
}
void Caller::generateInterArrivalTime()
{
e1.seed(rd1());
exponential_distribution<>callNums(25);
iarrivalTime = callNums(e1);
}
double Caller::getInterArrivalTime()
{
return iarrivalTime;
}
void Caller::setArrivalTime(double t)
{
arrivalTime = t;
}
double Caller::getArrivalTime()
{
return arrivalTime;
}
My CallCenter.h file
class CallCenter
{
private:
vector<Caller> callers;
priority_queue<Caller, vector<Caller>, CompareFunction > callQ;
public:
CallCenter();
void queueCalls();
void assignArrivalTime();
My CallCenter.Cpp file
CallCenter::CallCenter(): callers(10)
{
}
void CallCenter::assignArrivalTime()
{
for (int i = 0; i < callers.size(); i++)
{
callers[i].generateInterArrivalTime();
if (i==0)
{
callers[i].setArrivalTime(callers[i].getInterArrivalTime());
}
else {callers[i].setArrivalTime(callers[i - 1].getArrivalTime() + callers[i].getInterArrivalTime());}
cout << callers[i].getInterArrivalTime() << "\t" << callers[i].getArrivalTime() << endl;
}
}
void CallCenter::queueCalls()
{
for (int i = 0; i < callers.size(); i++)
{
callQ.push(callers[i]);
}
}
My CompareFunction.h file
#pragma once
#include "Caller.h"
class CompareFunction
{
public: bool operator()(Caller& lowp, Caller& highp)
{
return lowp.getArrivalTime() > highp.getArrivalTime();
}
};
random_device rd1;
Your class has a std::random_device as a class member.
std::random_device's copy constructor is deleted:
The copy constructor is deleted: std::random_device is not copyable
nor movable.
This makes this class, which contains this class member, also have a deleted copy constructor.
After all, if a class member cannot be copied, by default, then the class itself can't be copied by default either.
priority_queue<Caller, vector<Caller>, CompareFunction > callQ;
Your priority queue is based on a std::vector.
callQ.push(callers[i]);
std::vectors cannot be used with non-copyable/movable classes. You can only use std::vector with classes that can be copied or moved.
You will have to change your class design, in some form or fashion. The simplest change would be a priority queue of std::unique_ptrs or std::shared_ptrs to your Callers, which you will need to construct in dynamic scope (you will also have to provide a custom comparator class for std::priority_queue, so it knows how to prioritize the smart pointers correctly, this is a little bit of extra work but it's not too complicated once you have a complete grasp on all the moving pieces).
How to fix the function 'func' so that it returns the objects without being destroyed?
function 'func' must add the objects to a list and return them but be destroyed
The Smoothy abstract class has a purely virtual description method (). DecoratorSmoothy
contains a smoothy, description () and getPret () methods return the description and price
aggregate smoothy.
SmoothyCuFream and SmoothyCuUmbreluta classes add the text “cu crema”
respectively “cu umbreluta” in the description of the smoothy contained. The price of a smoothy that has the cream increases by 2 euro, the one with the umbrella costs an extra 3 euro.
BasicSmoothy class is a smoothy without cream and without umbrella, method
description () returns the name of the smothy
#include <iostream>
#include <vector>
using namespace std;
class Smoothy {
private:
int pret=0;
public:
virtual string descriere() = 0;
int getPret(){
return pret;
}
void setPret(int a) {
pret += a;
}
};
class BasicSmooty : public Smoothy {
private:
string nume;
public:
BasicSmooty(string n) :
nume { n } {}
string descriere() {
return nume;
}
};
class DecoratorSmoothy : public Smoothy {
private:
Smoothy* smooty;
public:
DecoratorSmoothy() = default;
DecoratorSmoothy(Smoothy* n) :
smooty{ n } {}
string descriere() {
return smooty->descriere();
}
int getPret() {
return smooty->getPret();
}
};
class SmootyCuFrisca : public DecoratorSmoothy {
private:
BasicSmooty bsc;
public:
SmootyCuFrisca(string desc) :
bsc{ desc } {}
string descriere() {
setPret(2);
return bsc.descriere() + " cu frisca ";
}
};
class SmootyCuUmbreluta : public DecoratorSmoothy{
private:
BasicSmooty bsc;
public:
SmootyCuUmbreluta(string desc) :
bsc{ desc } {}
string descriere() {
setPret(3);
return bsc.descriere() + " cu umbreluta ";
}
~SmootyCuUmbreluta() {
cout << "rip";
}
};
vector<Smoothy*> func(void)
{
std::vector<Smoothy*> l;
SmootyCuFrisca a1{ "smooty de kivi" };
SmootyCuUmbreluta a2{ "smooty de kivi" };
SmootyCuFrisca a3{ "smooty de capsuni" };
BasicSmooty a4{ "smooty simplu de kivi" };
l.push_back(&a1);
l.push_back(&a2);
l.push_back(&a3);
l.push_back(&a4);
return l;
}
int main() {
vector<Smoothy*> list;
// Here when i call func() objects are distroyed
list = func();
return 0;
}
In func you are storing the address of function local variables in l. So when you return l from the function, all the Smoothy* are now pointing to invalid memory.
To fix this, you can allocate memory for each pointer you add to l, like this:
l.push_back(new Smoothy{a1}); // instead of l.push_back(&a1);
// etc. for a2, a3, ...
To really get away from this problem, consider not using pointers at all. If your design doesn't need it, you can get rid of the pointers, and you'll save yourself a lot of trouble.
Well, when a method returns, of course all local/automatic variables are destroyed. Under the late revision c++ changes, there is the return && modifier, which invokes move semantics, which means for not const local/automatic objects you return, it steals: clones the returned object, making a new object and copying all the primitives and object pointers, then sets the object pointers to null so they cannot be deleted/freed by the destructor. (Note that C free of a null pointer does nothing!) For const, of course, it must deep copy.
I come from C/C# language and now I'm trying to learn about C++ and his standards functions.
Now, I'm creating a class called IMonsterDead. I will have a std::vector<IMonsterDead*> with N monsters.
Example:
class IMonsterDead {
public:
IMonsterDead(int Id)
{
this->_Id = Id;
}
virtual void OnDead() = 0;
int Id() const {
return _Id;
}
private:
int _Id;
};
One class which implements that class:
class MonsterTest : public IMonsterDead {
public:
MonsterTest(int generId)
: IMonsterDead(generId)
{
}
virtual void OnDead()
{
std::cout << "MonsterTesd died" << std::endl;
}
};
Ok, if I access directly everything works fine. But I'm trying to use std::find.
Full program test:
int main()
{
std::vector<IMonsterDead*> monsters;
for (int i = 0; i < 1000; i++)
{
monsters.emplace_back(new MonsterTest(1000 + i));
}
int id = 1033;
std::vector<IMonsterDead*>::iterator result = std::find(monsters.begin(), monsters.end(), [id]( IMonsterDead const* l) {
return l->Id() == id;
});
if (result == monsters.end())
std::cout << "Not found" << std::endl;
else
{
// Here I want to access OnDead function from result
}
return 0;
}
So I need to access OnDead function from result but I can't. Intellisense doesn't show anything for me. The result exists.
How can I access that function? Have another better way to do that?
You need to use std::find_if() instead of std::find(). std::find() is for finding an element with a specific value, so you have to pass it the actual value to find, not a user_defined predicate. std::find_if() is for finding an element based on a predicate.
Either way, if a match is found, dereferencing the returned iterator will give you a IMonsterDead* pointer (more accurately, it will give you a IMonsterDead*& reference-to-pointer). You need to then dereference that pointer in order to access any members, like OnDead().
You are also leaking memory. You are not delete'ing the objects you new. And when dealing with polymorphic types that get deleted via a pointer to a base class, the base class needs a virtual destructor to ensure all derived destructors get called properly.
With that said, you are clearly using C++11 or later (by the fact that you are using vector::emplace_back()), so you should use C++11 features to help you manage your code better:
You should use std::unique_ptr to wrap your monster objects so you don't need to delete them manually.
You should always use the override keyword when overriding a virtual method, to ensure you override it properly. The compiler can catch more syntax errors when using override than without it.
You should use auto whenever you declare a variable that the compiler can deduce its type for you. Especially useful when dealing with templated code.
Try something more like this:
#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
class IMonsterDead {
public:
IMonsterDead(int Id)
: m_Id(Id)
{
}
virtual ~IMonsterDead() {}
virtual void OnDead() = 0;
int Id() const {
return m_Id;
}
private:
int m_Id;
};
class MonsterTest : public IMonsterDead {
public:
MonsterTest(int generId)
: IMonsterDead(generId)
{
}
void OnDead() override
{
std::cout << "MonsterTest died" << std::endl;
}
};
int main()
{
std::vector<std::unique_ptr<IMonsterDead>> monsters;
for (int i = 0; i < 1000; i++)
{
// using emplace_back() with a raw pointer risks leaking memory
// if the emplacement fails, so push a fully-constructed
// std::unique_ptr instead, to maintain ownership at all times...
monsters.push_back(std::unique_ptr<IMonsterDead>(new MonsterTest(1000 + i)));
// or:
// std::unique_ptr<IMonsterDead> monster(new MonsterTest(1000 + i));
// monsters.push_back(std::move(monster));
// or, if you are using C++14 or later:
// monsters.push_back(std::make_unique<MonsterTest>(1000 + i));
}
int id = 1033;
auto result = std::find_if(monsters.begin(), monsters.end(),
[id](decltype(monsters)::value_type &l) // or: (decltype(*monsters.begin()) l)
{
return (l->Id() == id);
}
// or, if you are using C++14 or later:
// [id](auto &l) { return (l->Id() == id); }
);
if (result == monsters.end())
std::cout << "Not found" << std::endl;
else
{
auto &monster = *result; // monster is 'std::unique_ptr<IMonsterDead>&'
monster->OnDead();
}
return 0;
}
Iterators are an interesting abstraction, in this case to be reduced to pointers.
Either you receive the pointer to the element or you get an invalid end.
You can use it as a pointer: (*result)->func();
You can also use it to create a new variable:
IMonsterDead &m = **result;
m.func();
This should give the same assembly, both possible.
Is possible create a queue for differents types of Objects, but with same interface?
As example, I have an interface called SensorItem, and 4 kinds of Class, SensorItemA
,SensorItemB,
SensorItemC
,SensorItemD
`
queue <SensorItem> cola;
void encolar(SensorItem* dato)
{
cola.push (*dato);
}
SensorItem* sacar()
{
SensorItem* d=cola.front();
cola.pop();
return d;
}
Thats my class Queue(Cola)
and here i try to use it
void main()
{
Cola c=new Cola();
TemperatureItem t=new TemperatureItem(3.25);
c.encolar(t);
ImuItem i=new ImuItem(3,4,8);
}
its something wrong in my syntax? or just is not possible to do it?
Polymorphism in C++ only works with references and pointers. Objects in C++ are objects, not references. If you create a SensorItem it will always be a SensorItem, not a TemperatureItem or a ImuItem. If you have a std::queue<SensorItem>, it's elements will always be SensorItems, never TemperatureItems or ImuItems.
If you want to make a queue of objects derived from SensorItem, you need to use a queue of pointers to SensorItems:
#include <iostream>
#include <queue>
#include <memory>
struct SensorItem
{
virtual void doAThing() = 0;
virtual ~SensorItem() {}
};
struct TemperatureItem : SensorItem
{
void doAThing() { std::cout << "TemperatureItem\n"; }
};
struct ImuItem : SensorItem
{
void doAThing() { std::cout << "ImuItem\n"; }
};
class Cola
{
private:
std::queue<std::unique_ptr<SensorItem>> cola;
public:
void encolar(std::unique_ptr<SensorItem> dato)
{
cola.push(std::move(dato));
}
std::unique_ptr<SensorItem> sacar()
{
std::unique_ptr<SensorItem> d = std::move(cola.front());
cola.pop();
return d;
}
};
int main()
{
Cola c;
c.encolar(std::make_unique<TemperatureItem>());
c.encolar(std::make_unique<ImuItem>());
std::unique_ptr<SensorItem> item = c.sacar();
item->doAThing();
item = c.sacar();
item->doAThing();
}
Live on Coliru
Here I've used std::unique_ptr to avoid having to do manual memory management. You could use raw SensorItem*s, but I would advise against it.
I have a class that stores weak_ptrs in a container and later does something if the weak_ptr is not expired:
class Example
{
public:
void fill(std::shared_ptr<int> thing)
{
member.push_back(thing);
}
void dosomething() const
{
for (const auto& i : member)
if (!i.expired())
;// do something. the weak_ptr will not be locked
}
private:
std::vector<std::weak_ptr<int>> member;
};
If Example is an object that lives forever and fill is used regularily, the vector allocates memory for elements continously, but they are never removed after they expired.
Is there any automatic C++ way to get rid of the expired weak_ptrs in the container or is there a better way to store a variable number of them?
My naive way would be to iterate over the container each time fill is called and remove all the expired weak_ptrs. In scenarios where Example has many elements in the container and fill is frequently called this seems to be very inefficient.
Since you clarified that you are actually using a std::map and not a std::vector, it might be easiest to remove the expired elements on-the-fly in doSomething(). Switch back from a range-based for loop to a normal iterator based design:
void dosomething() const
{
auto i = member.begin();
while( i != member.end() ) {
if( i->expired() ) { i = member.erase( i ); continue; }
;// do something. the weak_ptr will not be locked
++i;
}
}
Does the shared_ptr<int> have to be a shared_ptr<int>?
How about a shared_ptr<IntWrapper>?
#include <iostream>
#include <forward_list>
using namespace std;
class IntWrapper {
public:
int i;
static forward_list<IntWrapper*>& all() {
static forward_list<IntWrapper*> intWrappers;
return intWrappers;
}
IntWrapper(int i) : i(i) {
all().push_front(this);
}
~IntWrapper() {
all().remove(this);
}
};
void DoSomething() {
for(auto iw : IntWrapper::all()) {
cout << iw->i << endl;
}
}
int main(int argc, char *argv[]) {
shared_ptr<IntWrapper> a = make_shared<IntWrapper>(1);
shared_ptr<IntWrapper> b = make_shared<IntWrapper>(2);
shared_ptr<IntWrapper> c = make_shared<IntWrapper>(3);
DoSomething();
return 0;
}
I would rather use a custom deleter for the shared_ptr. But this implies here to change the interface of the Example class. The advantage using custom deleter is that there is no need to check for expired objects in the collection. The collection is directly maintained by the custom deleter.
Quick implementation :
#include <memory>
#include <iostream>
#include <set>
template <typename Container>
// requires Container to be an associative container type with key type
// a raw pointer type
class Deleter {
Container* c;
public:
Deleter(Container& c) : c(&c) {}
using key_type = typename Container::key_type;
void operator()(key_type ptr) {
c->erase(ptr);
delete ptr;
}
};
class Example {
public:
// cannot change the custom deleter of an existing shared_ptr
// so i changed the interface here to take a unique_ptr instead
std::shared_ptr<int> fill(std::unique_ptr<int> thing) {
std::shared_ptr<int> managed_thing(thing.release(), Deleter<containter_type>(member));
member.insert(managed_thing.get());
return managed_thing;
}
void dosomething() const {
// we don't need to check for expired pointers
for (const auto & i : member)
std::cout << *i << ", ";
std::cout << std::endl;
}
using containter_type = std::set<int*>;
private:
containter_type member;
};
int main()
{
Example example;
auto one = example.fill(std::unique_ptr<int>(new int(1)));
auto two = example.fill(std::unique_ptr<int>(new int(2)));
auto three = example.fill(std::unique_ptr<int>(new int(3)));
example.dosomething();
three.reset();
example.dosomething();
}