c++ however to avoid deep copy issue

for the below code demo, I send a reference into a class, and add some items to the vector, then return the vector, I think there is copy issue in the assignment test = a.return_data() in the main function, is there some method to improve the efficiency?

#include <iostream>
#include <stdio.h>
#include <vector>

using namespace std;

class A 
{
public:
    A(vector<int> &a);
    void additem(int c);
    vector<int> return_data();
private:
    vector<int> d;
};

A::A(vector<int> &a)
  {
      d = a;
  }

void A::additem(int c)
{
      d.push_back(c);
}

vector<int> A::return_data()
{
    return d;
}

void main()
{
    vector<int> test;

    for(int i=0; i<10; i++)
    {
        test.push_back(i);
    }
    cout << test.size() << endl;
    A a(test);
    a.additem(10);
    test = a.return_data();
    cout << test.size() << endl;
}


Source: c++

Leave a Reply