Reputation: 8154
I'm having the following (simplified) class:
class Operator {
private:
std::map<std::string, std::unique_ptr<Operand>> op;
public:
template <class T>
void insertOperand(std::string const &s, T o = T()) {
op.insert(std::pair<std::string, std::unique_ptr<StreamOperand>>(
s, std::move(std::unique_ptr<T>(new T(o)))
);
}
void setOperandsValue(std::string const &o, int v) {
op.find(o)->second->setValue(v);
}
};
Inserting a new Operand
works without any problems. However, when the function returns the destructor gets called and thus the map
does not contain any object when calling setOperandsValue
. I've observed this using DDD: at the end of insertOperand
Operator::~Operator()
is called.
After looking at Using std::unique_ptr with STL, I introduced (better: used) std::move
but either it's not placed correctly or I am missing something (highly probable due to lack of knowledge). I'm not using map::emplace
because it's not available.
Edit: The destructor call is valid, since it's destroying new T(o)
. Anyway, the map
remains empty when entering setOperandsValue
.
Edit #2: On entering setOperandsValue
and performing op.find(o)
the result is op.end
, i.e. entry not found although I've added it before.
Upvotes: 4
Views: 3151
Reputation: 227390
I don't think your pointer is getting destroyed. What you are seeing here:
template <class T>
void insertOperand(std::string &s, T o = T()) {
op.insert(std::pair<std::string, std::unique_ptr<StreamOperand>>(
s, std::move(std::unique_ptr<T>(new T(o)))
);
}
is the destruction of o
, after it has been used to construct the heap allocated T
used in the unique_ptr
.
The map being empty is not a symptom of the pointer being destroyed. If this were the case (the pointer being destroyed), you would have an entry in the map for a given key, with an invalid unique_ptr.
Upvotes: 3