creating a shared_ptr from unique_ptr

后端 未结 3 848
北荒
北荒 2021-02-04 23:17

In a piece of code I reviewed lately, which compiled fine with g++-4.6, I encountered a strange try to create a std::shared_ptr from std::unique_

3条回答
  •  别那么骄傲
    2021-02-05 00:07

    This shouldn't compile. If we disregard the uniqueness and sharedness of the pointers for a moment, it's basically trying to do this:

    int *u = new int;
    int *s = new int(std::move(u));
    

    It means it's dynamically creating an int and initialising it with an rvalue reference to std::unique_ptr. For ints, that simply shouldn't compile.

    For a general class Foo, it depends on the class. If it has a constructor taking a std::unique_ptr by value, const ref or rvalue ref, it will work (but maybe not do what the author intended). In other cases, it shouldn't compile.

提交回复
热议问题