I need a function which returns a shared_ptr to a vector containing a large number of objects. The following code realizes this but one can see that copy constructors are called for an extra number of times.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class A {
public:
int IA ;
A(int ia) {
cout << "Constructor is called\n" ;
IA = ia ;
}
A(const A& a) {
cout << "Copy constructor is called\n" ;
IA = a.IA ;
}
} ;
shared_ptr<vector<A>> foo() {
vector<A> myA ;
myA.push_back(A(10)) ;
myA.push_back(A(20)) ;
return make_shared<vector<A>>(myA) ;
}
int main() {
shared_ptr<vector<A>> myA ;
myA = foo() ;
return 0 ;
}
In real cases, A may also be bigger, so to make_shared<vector<A>>(myA) ; would cause unncessary copying process. I wonder if there is any way to reduce copy constructor calling times.