-2

I have to write a generic data structure that resembles a C++ vector as part of an assignment.

This is my idea for the Vector:

template<typename T>
class MyVector {
private:
    T* data_;
    size_t size_;
public:
    MyVector();
    MyVector(const MyVector &otherVector);

    // which one should I use?
    add(const T& value);
    add(T value);

    ~MyVector();
};

Now I wonder how to pass values to the methods. Coming from Java I am a bit overwhelmed. In Java you wouldn't hesitate and pass the value by reference, the GC would never delete the object if it is still referenced.

In C++ you would create a mess if you would pass by reference considering code like this:

void myFunction(MyVector &myVector) {
    int a = 5;

    myVector.add(a);
}

int main() {

    auto vector = MyVector<int>();

    myFunction(vector);

    // now the vector contains a reference to 
    // something that doesn't exist anymore.
}

How do you solve this problem? Would you just pass by reference and create a copy or do you pass by value (which creates a copy for you)

Looking at the C++ std::vector interface I see that they use references.

I just don't see the value of passing by reference if you have to create your own copy.

TimKaechele
  • 510
  • 5
  • 12
  • If you down vote this question could you please name a reason? – TimKaechele Mar 29 '16 at 00:51
  • I suspect you don't have a precise idea of the meaning of "passing an object by reference" in C ++. It's false that "pass by reference and create a copy"; passing by reference it's the c++ way to avoid a copy creation. I suggest you to read carefully this answer: http://stackoverflow.com/a/5922217/6022656 – max66 Mar 29 '16 at 07:02

1 Answers1

1

add(const T& value) is ok, you just should be sure that there is properly defined assign operator for T. So, the implementation will be:

void Add(const T& value) {
    if (m_size == m_maxSize) realloc(); // stuff to have enough space
    m_data[m_size++] = value; // here copy is creating
}

default impl of assign operator just byte-copy fields of class, it is not always correct.

Other solution, if you want more java-style semantic, is to make T = shared_ptr<YourType> or T = YourType* The latter is rather difficult because require skill of manual lifetime control, so is undesirable for c++ beginners.

void myFunction(MyVector<shared_ptr<X>> & myVector) 
{
    shared_ptr<X> x(new X(...));
    myVector.add(x);
}

works similar to references in Java. Other way, that was used in old times:

template<typename T>
class MyVector {
private:
    T** data_; // now you have array of pointers, so should be careful
....
    add(T* value);
....
}

void myFunction(MyVector<X> & myVector) 
{
    X * x = new X(...);
    myVector.add(x); // now x belongs to myVector and it should handle its lifetime
}
aaalex88
  • 619
  • 4
  • 13