I am getting the values of the vector size as 1
and 0
I know there are 2 different instances but I want it to be common between both the instances
I am not sure what would be the right approach need some insights on what will suffice in my case.
#include <iostream>
#include <memory>
#include <vector>
class Fruit
{
public:
Fruit(std::vector<int>& number);
Fruit();
int numOfApple();
private:
std::vector<int> number;
};
Fruit::Fruit() {}
class Apple
{
public:
Apple();
Apple(Fruit &fruit);
int appleCount();
private:
Fruit fruit;
};
Apple::Apple() {}
Apple::Apple(Fruit &fruit):fruit(fruit) {}
int Fruit::numOfApple()
{
std::cout<<"vector size is"<<number.size()<<std::endl;
for (auto& fruz : number) {
std::cout<<"do nothing"<<std::endl;
}
return 0;
}
int Apple::appleCount()
{
fruit.numOfApple();
return 0;
}
Fruit::Fruit(std::vector<int>& number):number(number) {}
int main()
{
std::vector<int> fru;
fru.push_back(1);
Fruit fruit1(fru);
Apple apple(fruit1);
fruit1.numOfApple(); // the size of the vector here is 1
// Now try to simulate server code
Fruit fruit2;
fruit2.numOfApple(); // the size of vector in this is 0
return 0;
}
Output
./a.out vector size is1 do nothing vector size is0
You can use a std::shared_ptr
for this purpose. It lives as long as any of the objects referencing it are alive and allows multiple objects to share ownership of its contents.
class Fruit
{
Fruit::Fruit()
: number(std::make_shared<std::vector<int>>())
{}
Fruit(std::vector<int>& numberNew)
: number(std::make_shared<std::vector<int>>(numberNew))
{}
std::shared_ptr<std::vector<int>> number;
}
Now when your class is copied, the copy of the shared_ptr
will not copy the vector but just refer to the same one and deal with all lifetime management for you.
int Fruit::numOfApple()
{
std::cout << "vector size is" << number->size() << std::endl;
for (auto& fruz : *number) {
std::cout << "do nothing" << std::endl;
}
return 0;
}
I strongly advise against making anything static
unless that is absolutely necessary. It is not necessary here, and you can prevent future growth pains by going for a proper solution right now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With