C++: Passing object to class constructor, how is it stored?
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
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.