Skip to content

Commit 0298470

Browse files
committed
improved example 6
1 parent af243ad commit 0298470

File tree

2 files changed

+15
-16
lines changed

2 files changed

+15
-16
lines changed

examples/ex06_access_by_ptr.cpp

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,25 @@ class PushIntoVector : public SyncActionNode
1919
const int number = getInput<int>("value").value();
2020
if(auto any_ptr = getLockedPortContent("vector"))
2121
{
22-
// inside this scope, any_ptr provides a mutex-protected,
23-
// thread-safe way to access an element inside the blackboard.
24-
if(auto vect_ptr = any_ptr->castPtr<std::vector<int>>())
22+
// inside this scope (as long as any_ptr exists) the access to
23+
// the entry in the blackboard is mutex-protected and thread-safe.
24+
25+
// check if the entry contains a valid element
26+
if(any_ptr->empty())
2527
{
26-
vect_ptr->push_back(number);
27-
std::cout << "Value ["<< number <<"] pushed into the vector. New size: "
28-
<< vect_ptr->size() << "\n";
29-
}
30-
else {
31-
// This happens when the entry of the blackboard is empty or if
32-
// we tried to cast to the wrong type.
33-
// Let's insert a new vector<int> with a single value
28+
// The entry hasn't been initialized by any other node, yet.
29+
// Let's initialize it ourselves
3430
std::vector<int> vect = {number};
3531
any_ptr.assign(vect);
3632
std::cout << "We created a new vector, containing value ["<< number <<"]\n";
3733
}
34+
else if(auto* vect_ptr = any_ptr->castPtr<std::vector<int>>())
35+
{
36+
// NOTE: vect_ptr would be nullptr, if we try to cast it to the wrong type
37+
vect_ptr->push_back(number);
38+
std::cout << "Value ["<< number <<"] pushed into the vector. New size: "
39+
<< vect_ptr->size() << "\n";
40+
}
3841
return NodeStatus::SUCCESS;
3942
}
4043
else {

include/behaviortree_cpp/utils/locked_reference.hpp

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,6 @@ class LockedPtr {
5858
}
5959
}
6060

61-
bool empty() const {
62-
return ref_ == nullptr;
63-
}
64-
6561
const T* get() const{
6662
return ref_;
6763
}
@@ -85,7 +81,7 @@ class LockedPtr {
8581
{
8682
*ref_ = other;
8783
}
88-
else if constexpr( std::is_same_v<BT::Any, OtherT>)
84+
else if constexpr(std::is_same_v<BT::Any, OtherT>)
8985
{
9086
other->copyInto(*ref_);
9187
}

0 commit comments

Comments
 (0)