0
// FUNCTION TEMPLATE make_unique
template <class _Ty, class... _Types, enable_if_t<!is_array_v<_Ty>, int> = 0>
_NODISCARD unique_ptr<_Ty> make_unique(_Types&&... _Args) { // make a unique_ptr
    return unique_ptr<_Ty>(new _Ty(_STD forward<_Types>(_Args)...));
}

I see this code in the visual studio 2019's stl code. I guess it can work normally because of the C++ movement semantics, but when I write a test code for it, I found that the return code will not invoke the move constructor or move assignment.this is the demo codes:

#include <iostream>
#include <thread>
#include <coroutine>
#include <chrono>
#include <functional>
#include <mutex>

class TestNotCopyable
{
public:
    TestNotCopyable& operator = (const TestNotCopyable&) = delete;
    TestNotCopyable(const TestNotCopyable&) = delete;

    TestNotCopyable(int a) :
        data(a)
    {
        std::cout << "constructor " << a << " " << (std::size_t)(void*)this << std::endl;
    }

    TestNotCopyable(TestNotCopyable&& other) noexcept :
        data(other.data)
    {
        other.data = 0;

        std::cout << "move constructor " << data << " " << (std::size_t)(void*)this << " other:"<< (std::size_t)(void*)&other << std::endl;
    }

    TestNotCopyable& operator =(TestNotCopyable&& other) noexcept = default;
    
    ~TestNotCopyable()
    {
        std::cout << "destructor " << data << " " << (std::size_t)(void*)this << std::endl;
    }
private:
    int data;
};

TestNotCopyable make_object(int t)
{
    return TestNotCopyable(t); // question 1: why this function will not invoke move constructor?
}

TestNotCopyable make_object2(int t)
{
    TestNotCopyable tt(t);
    return tt; // compile success // invoke move constructor...
}


int main()
{
    auto a = make_object(100);
    auto c = make_object2(200);

    //  auto b = a; // compile error !!! can't copy, this is correct.
}

the output is :

constructor 100 265004447028
constructor 200 265004446708
move constructor 200 265004447060 other:265004446708
destructor 0 265004446708
destructor 200 265004447060
destructor 100 265004447028

F:\Projects\ConsoleApplication6\x64\Debug\ConsoleApplication6.exe (进程 29520)已退出,代码为 0。
按任意键关闭此窗口. . .

So I want to ask, how does the function make_object realize the construction of the TestNotCopyable object?How does it put the temporary object inside make_object into the local variable a?What is the essential difference between make_object and make_object2?

boo
  • 361
  • 3
  • 15

0 Answers0