TheRocinante
TheRocinante

Reputation: 4201

Is passing by reference the right solution?

I have some type like this:

#pragma once

#include <stdio.h>
#include <string>

struct Color {
    std::string value;
};

struct Shirt {
    std::string brand;
    Color color;
};

class Outfit {
public:
    Outfit(Shirt shirt):
        shirt(shirt) {}

private:
    Shirt shirt;
};

I previously reviewed this Stackoverflow thread on this topic.

Let me explain my thinking, and I'd like for anyone here to tell me if I'm correct or incorrect or if there's something I didn't consider or misunderstood.

My current understanding is I should pass in the arguments as const reference. If I pass by value, then when I create an instance of Outfit, for example, Shirt will be be copied. If I understood correctly, this might be dangerous. The copy and the original Outfit will point to the same Shirt instance. And this shared ownership model is dangerous because we don't know if Shirt gets released.

Is that understanding correct? Or am I overcomplicating this?

Upvotes: 0

Views: 69

Answers (1)

smac89
smac89

Reputation: 43078

The copy and the original Outfit will point to the same Shirt instance

No this is wrong. A copy has no relationship to the original except if it also contains pointers. In that case, the pointers will still point to whatever they referred to before the copy was made. However, even the pointers themselves are not the same. So doing anything that may affect the pointer such as incrementing (pointer++) will not affect the other pointer.

In either

Outfit(Shirt shirt): shirt(shirt) {}

or

Outfit(const Shirt& shirt): shirt(shirt) {}

A copy is made.

How it is done depends on which one you choose. I would argue that the second option is preferred because only the copy constructor is called to make a copy of the shirt parameter, but the first will make a copy and then the move constructor is used to "move" the copy into the shirt field.

Upvotes: 1

Related Questions