Please take a look at this code:
template <typename T>
class matrix
{
private:
std::vector<T> vec_;
public:
matrix(size_t rows , size_t cols) : rows_(rows) , cols_(cols) , vec_(rows_ * cols_)
{
}
size_t rows_;
size_t cols_;
};
This is a way to declare a class. I am just wondering where the std::vector
is being allocated and where it is being initialized?
What happens when I declare a variable? Is the space for it allocated in the stack before the constructor is called or is allocated and initialized in the constructor?
What is the difference between declaring a vector with size 10
std::vector<T> vec_(10);
and calling the constructor of vec_ with the size 10 in the constructor?
matrix() : vec_(10)
I wanted to understand how objects are allocated and initialized in C++.
Also I can create a constructor without calling the constructor of std::vector
matrix() {}
What is happening here? Since I am not calling the constructor for the vector does the compiler call it own its own? Can the vector object utilized? Or is it called automatically because I declared std::vector
to be a variable in my class?
Also does initializing as std::vector vec(10)
, have the same effect as calling resize/reserve. Which is it closer to?