Raees Rajwani
Raees Rajwani

Reputation: 517

Reference binding and the copy constructor/move constructor

If I have a function like so:

int foo(std::vector<int>* integer1ArrayIn, * integer2ArrayIn) {
    std::vector<int>& integer1Array = *integer1ArrayIn;
    std::vector<int>& integer2Array = *integer2ArrayIn;
}
  1. Will the reference integer1Array be calling a copy constructor/move constructor to copy over the elements of the passed in parameter?
  2. Does binding a reference to a dereferenced pointer call the copy constructor?
  3. In what circumstances does reference binding invoke a copy constructor?
  4. Can someone explain what happens as this code executes in memory?

Thank you

Upvotes: 1

Views: 99

Answers (2)

Jonas
Jonas

Reputation: 7017

1) No, there are no copies made. You can test it with a small program, like this.

#include <iostream>

struct foo
{
    foo() { std::cout << "Constructor" << std::endl; }  
    foo(const foo&) { std::cout << "Copy constructor" << std::endl; }
    foo& operator=(const foo&) { std::cout << "Copy assignment operator" << std::endl; }    
};

int main() {
    foo* A = new foo;
    foo& B = *A;
    delete A;
}

2) Beware of nullptrs! Otherwise all is fine.

3) Never (see answer by AlexG)

4) Not sure what you mean by "code executes in memory", since code is not executed in memory. If you mean what happens to the memory when the program is executed, then that's another story

Upvotes: 2

AlexG
AlexG

Reputation: 1103

  1. No.
  2. No, but it would crash badly if it was nullptr. Consider passing by reference whenever a parameter HAS to be there, and pass by pointer when a parameter MIGHT be there (but always verify for nullptr too!).
  3. Whenever the l-value (in this case integer1Array and integer2Array) are pointers or references, it will never call copy/move constructor.

if you had std::vector integer1Array = *integer1ArrayIn it would effectively make a copy.

You can use Jonas's answer to play around with and see for yourself :)

Upvotes: 2

Related Questions