M
Marcus Kwok
I am utilizing a std::vector<int>, but due to a platform-specific reason
(Managed C++, but this is irrelevant), in order to include it as a
member of a class, I have to work with a pointer to it. However, I can
declare concrete std::vectors as local variables in functions.
Therefore, I would like to know whether the following construct is safe,
i.e., there is no memory leak or undefined behavior. The demonstration
example doesn't need all the class boilerplate so I left that out.
Specifically, is it safe to call vector::swap() through a pointer to a
vector? As far as I can reason, it should be OK, and adding output
statements shows that *pv has the correct values, but I want to confirm
whether or not this is undefined behavior that just happens to work by
coincidence.
#include <vector>
int main()
{
using std::vector;
vector<int>* pv = new vector<int>; // This represents my class variable
vector<int> v; // This represents the local variable
for (int i = 0; i < 3; ++i) {
v.push_back(i);
}
pv->swap(v); // <----- I would like to know if this is safe
delete pv;
}
(Managed C++, but this is irrelevant), in order to include it as a
member of a class, I have to work with a pointer to it. However, I can
declare concrete std::vectors as local variables in functions.
Therefore, I would like to know whether the following construct is safe,
i.e., there is no memory leak or undefined behavior. The demonstration
example doesn't need all the class boilerplate so I left that out.
Specifically, is it safe to call vector::swap() through a pointer to a
vector? As far as I can reason, it should be OK, and adding output
statements shows that *pv has the correct values, but I want to confirm
whether or not this is undefined behavior that just happens to work by
coincidence.
#include <vector>
int main()
{
using std::vector;
vector<int>* pv = new vector<int>; // This represents my class variable
vector<int> v; // This represents the local variable
for (int i = 0; i < 3; ++i) {
v.push_back(i);
}
pv->swap(v); // <----- I would like to know if this is safe
delete pv;
}