Home > other >  C : Passing object to class constructor, how is it stored?
C : Passing object to class constructor, how is it stored?

Time:01-11

Consider the following example of a simple class implementation in C .

foo.hpp

#include <vector>
class Foo {
private:
    std::vector<double> X;
public:
    Foo() = default;
    ~Foo() = default;
    Foo(std::vector<double>&);
};

foo.cpp

#include "Foo.hpp"
Foo::Foo(std::vector<double>& X):
        X(X)
{}

In this case, the vector X is passed by reference to the constructor of the class Foo. I start having doubts, though, on whether the operation X(X) in the implementation makes a copy and pastes it "in" the member X of the class.

Which is it?

CodePudding user response:

Yes, the data member X will be copy-initialized from the constructor parameter X.

If you declare the data member X as reference, then no copy operation happens. E.g.

class Foo {
private:
    std::vector<double>& X;
public:
    ~Foo() = default;
    Foo(std::vector<double>&);
};

Foo::Foo(std::vector<double>& X):
        X(X)
{}

Then

std::vector<double> v;
Foo f(v); // no copies; f.X refers to v

CodePudding user response:

Rest assured. The member's type is vector<double>, so the compiler will look for a constructor overload in the vector<double> class that matches the provided argument type (vector<double>&).

The best match it will find is the const vector<double>& overload - the copy constructor.

CodePudding user response:

As an alternative to this, you can create a constructor with an rvalue reference for the class:

#include <vector>
class Foo {
private:
    std::vector<double> X;
public:
    Foo() = default;
    ~Foo() = default;
    Foo(const std::vector<double>&);
    Foo(std::vector<double>&&);
};

Then the constructor would be implemented like this:

Foo::Foo(std::vector<double>&& X_) : X(std::move(X_)) {}

No copy is done when this constructor is invoked.

  •  Tags:  
  • Related