Skip to content

Commit 588dbbd

Browse files
committed
fix shared_ptr self assignments
see open-telemetry#3713 (comment)
1 parent b568e71 commit 588dbbd

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

api/include/opentelemetry/nostd/shared_ptr.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,10 @@ class shared_ptr
119119

120120
shared_ptr &operator=(shared_ptr &&other) noexcept
121121
{
122+
if (this == &other)
123+
{
124+
return *this;
125+
}
122126
wrapper().~shared_ptr_wrapper();
123127
other.wrapper().MoveTo(buffer_);
124128
return *this;
@@ -132,6 +136,10 @@ class shared_ptr
132136

133137
shared_ptr &operator=(const shared_ptr &other) noexcept
134138
{
139+
if (this == &other)
140+
{
141+
return *this;
142+
}
135143
wrapper().~shared_ptr_wrapper();
136144
other.wrapper().CopyTo(buffer_);
137145
return *this;

api/test/nostd/shared_ptr_test.cc

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <vector>
1010

1111
#include "opentelemetry/nostd/shared_ptr.h"
12+
#include "opentelemetry/nostd/unique_ptr.h"
1213

1314
using opentelemetry::nostd::shared_ptr;
1415

@@ -96,6 +97,15 @@ TEST(SharedPtrTest, MoveConstructionFromStdSharedPtr)
9697
EXPECT_EQ(ptr2.get(), value);
9798
}
9899

100+
TEST(SharedPtrTest, MoveConstructionFromNoStdUniquePtr)
101+
{
102+
opentelemetry::nostd::unique_ptr<int> value(new int{123});
103+
auto p = value.get();
104+
shared_ptr<int> ptr{std::move(value)};
105+
EXPECT_EQ(value.get(), nullptr); // NOLINT
106+
EXPECT_EQ(ptr.get(), p);
107+
}
108+
99109
TEST(SharedPtrTest, Destruction)
100110
{
101111
bool was_destructed{};

0 commit comments

Comments
 (0)