I'm trying to understand how I should use smart pointers efficiently, and I got curious about how they work together with rvalue references. How come std::make_shared
(and presumably make_unique
as well) uses copy semantics and not move semantics?
Here's a gtest test that showcases what I'm trying to say
#include <memory>
int dtor_calls = 0;
struct MoveSemanticsTest1 {
int data;
~MoveSemanticsTest1() { dtor_calls++; }
};
void reset_move_dtor_calls() {
dtor_calls = 0;
}
TEST(MoveSemanticsSanityTest1, SanityTests) {
reset_move_dtor_calls();
{
MoveSemanticsTest1 a = MoveSemanticsTest1();
}
EXPECT_EQ(1, dtor_calls); // <-- This passes, makes sense
reset_move_dtor_calls();
{
MoveSemanticsTest1 b = {3};
auto a = std::make_shared<MoveSemanticsTest1>(std::move(b));
}
EXPECT_EQ(1, dtor_calls); // <-- This fails, why?
reset_move_dtor_calls();
{
MoveSemanticsTest1 b = {3};
auto a = std::make_shared<MoveSemanticsTest1>(b);
}
EXPECT_EQ(2, dtor_calls); // <-- This passes, makes sense because of the copying
}
The second EXPECT_EQ
fails, which hints to the moved b
resource doesn't actually move the resource.