user3524337 user3524337 - 7 days ago 6
C++ Question

Does this use of std::make_unique lead to non-unique pointers?

Suppose I have the following code in C++:

#include <memory>
#include <iostream>

struct Some {
Some(int _a) : a(_a) {}
int a;
};

int main() {
Some some(5);

std::unique_ptr<Some> p1 = std::make_unique<Some>(some);
std::unique_ptr<Some> p2 = std::make_unique<Some>(some);

std::cout << p1->a << " " << p2->a << std::endl;
return 0;
}


As I understand, unique pointers are used to guarantee that resources are not shared. But in this case both
p1
and
p2
point to the same instance
some
.

Please unveil the situation.

Answer

They don't point to the same resource, they both point to a copy of it. You can illustrate it by deleting the copy constructor to see the error:

#include <memory>
#include <iostream>

struct Some {
        Some(int _a) : a(_a) {}
        Some(Some const&) = delete;
        int a;
};

int main() {
        Some some(5);

        std::unique_ptr<Some> p1 = std::make_unique<Some>(some); //error here
        std::unique_ptr<Some> p2 = std::make_unique<Some>(some);

        std::cout << p1->a << " " << p2->a << std::endl;
        return 0;
}