1

My class contains a vector and upon instantiating it, I want to initialize its vector with some input vector:

class Test {
public:
    Test(std::vector<int>& input_vec) : vec(input_vec) {};
    std::vector<int> vec;
};

int main()
{
    std::vector<int> a{1,2,3};
    
    Test t(a);
}

I am passing a to Test's constructor by reference for efficiency-reasons in case the input vector is very large. I have two concerns in mind:

  1. Is it actually more efficient in my case to pass it by reference or is it redundant since I am only making a copy of it?
  2. Does it pose a memory risk that I pass a vector by reference and then take a copy of it?
Tyler D
  • 323
  • 1
  • 12
  • 1
    The dupe should answer your questions. If you have a specific question that is not answered there, edit the question. – cigien Sep 17 '20 at 14:05
  • @cigien This answer is so old and so focused on possible optimizations that it's hard to add any info about C++11... – Yksisarvinen Sep 17 '20 at 14:11
  • 1
    @Yksisarvinen Hmm, you're right. There must be a canonical dupe for this. If I find it, I'll edit the dupe target. I'd rather not reopen this though. – cigien Sep 17 '20 at 14:22
  • 1
    Added a more appropriate dupe. – cigien Sep 17 '20 at 14:27

0 Answers0