Is there any significant difference in performance, memory, etc, between:
- #1: moving a pointer to a temporary pointer, moving it back, then deleting the temporary pointer
- #2: copying a pointer to a temporary pointer, then deleting the temporary pointer
I have the following code, two pointer of objects a Base
and a Derived
(which is derived from Base) are allowed to be stored inside a vector of pointers of Base objects, when reading the vector I need to check whether I need to dynamic_pointer_cast
the pointer so data doesn't get sliced off.
#include "Base.h"
#include "Derived.h"
class Base
{
public:
Base() {};
~Base() {};
};
class Derived: public Base
{
public:
Derived() {};
~Derived() {};
};
int main()
{
std::vector<std::shared_ptr<Base>> vectorOfBaseObjects;
std::shared_ptr<Base> base = std::make_shared<Base>();
std::shared_ptr<Derived> derived = std::make_shared<Derived>();
myVec.push_back(base);
myVec.push_back(derived);
for (auto &it : vectorOfBaseObjects) {
// #1: Move pointer to a temporary location and move it back when done
if (std::shared_ptr<Derived> tmp_ptr = std::move(std::dynamic_pointer_cast<Derived>(it))) {
// Do something with the derived object
it = std::move(tmp_ptr);
}
// #2: Create a new temporary pointer
if (std::shared_ptr<Derived> tmp_ptr = std::dynamic_pointer_cast<Derived>(it)) {
// Do something with the derived object
}
}
}
Both statements work just fine, the only issues I could make of might be
- #1: missing pointer locations in multi threaded appications in very rare cases, which could become a problem.
- #2: an additional location assigned in the memory, which shoulnd't be an issue at all.
Aucun commentaire:
Enregistrer un commentaire