i have some trobles with the following code:
#include <iostream>
#incldue <vector>
template <typename ElemType>
class A{
private:
std::vector<ElemType> data;
public:
A() {};
A(int capacity) {
data.reserve(capacity);
}
int GetCapacity() {
return data.capacity();
}
};
int main() {
A<int> a;
a = A<int>(5);
std::cout << a.GetCapacity() << std::endl;
}
The output is 0. What can be the problem?
The copy-constructor and assignment operator of
std::vector<T>are not required to copy the capacity of the vector, only the elements. Because the linea = A<int>(5)indirectly invokes the assignment operator (after creating a temporary), the vector inadoes not have a capacity.Try changing the first two lines of main to just
A<int> a(5)and see what the results are.If you absolutely need the capability to transfer the capacity from one instance to another, you need to define the assignment and copy-constructor of A to both copy the data and assign the capacity.