C++ Object Constructor with Temporary Object as Argument

1.7k views Asked by At

I've written some code and it suddenly occurred to me that what I'm doing might be a really bad idea. Here is a sort of abstract example. The key point is the passing by reference of the vector.

// vector.hpp
class vector {
    vector(double x, double y, double z);
}

// particle.hpp
class particle {
    particle(const vector& _init_position);
    vector m_position;
}

So I have written some code to represent a class vector, which contains 3D vector stuff, and have also written a particle class, the position vector of which can be initialized with the constructor and a vector instance.

In my main() function, I was using a temporary object to initialize particle objects, like so:

int main() {

    particle my_particle(vector(0.0, 1.0, 2.0)); // Temp vector instance - problem?
}

Here you can see that a temporary vector instance is created, I assume it is placed on the stack somewhere, and then the constructor of particle is called.

Is this okay or is it an example of very bad code? I suspect the latter, as since I am passing by reference, and therefore the instance of the temp vector might not be valid?

Hopefully someone can clarify this?

2

There are 2 answers

3
Neil Kirk On BEST ANSWER

You are permitted to pass a temporary object to a function as either a value or const reference parameter. It is a good thing, as you can save copies when passing by const reference.

0
sfjac On

You don't show the implementation of the vector constructor, but the member is a value, so I assume the constructor is copying its argument to the member. If that's the case then passing a const ref is exactly what you want to do to avoid unnecessary copies.

What you don't want to do is hold on to a reference to (or address of) that argument.