c++ - 为什么我可以使用 make_unique 创建带有衰减数组指针的 unique_ptr?

标签 c++ c++11 c++14 unique-ptr

具体来说,我想知道为什么会这样编译:

#include <memory>
#include "make_unique.hpp"
void foo(const char *s){
   std::unique_ptr<const char*>ptr = std::make_unique<const char*>(s);
}

这不是:

#include <memory>
#include "make_unique.hpp"
void foo(const char *s){
   std::unique_ptr<const char*>ptr(s);
}

当我像在 make_unique 实现中一样编写它时似乎正在工作:

#include <memory>
#include "make_unique.hpp"
#include <iostream>
std::unique_ptr<const char*> foo(const char *s){
   /* return std::make_unique<const char*>(s); */
   return std::unique_ptr<const char*>(new decltype(s)(std::forward<decltype(s)>(s)));
}
int main(){
    const char * s = "bar";
    std::unique_ptr<const char*>ptr = foo(s);
    std::cout<<*ptr;

}

EDIT* 错误(截断)

 error: no matching conversion for functional-style cast from 'const char *' to 'std::unique_ptr<const char *>'
   return std::unique_ptr<const char*>(s);
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../../include/c++/4.9/bits/unique_ptr.h:169:7: note: candidate constructor not viable: no known
      conversion from 'const char *' to 'pointer' (aka 'const char **') for 1st argument; take the address of the argument with &
      unique_ptr(pointer __p) noexcept
      ^

最佳答案

  1. std::make_unique<T>(args...)期望构建一个 T来自 args... .

  2. std::unique_ptr<T>(p)期待 p成为 T * 类型的拥有值.

请注意,您的唯一指针模拟了一个 const char ** , 不是 const char * .所以在 (1) 中你创建了一个新的动态分配的 char 指针,它的值是从 s 复制的。 ,而在 (2) 中,您试图创建一个唯一的指针来获取某物的所有权,但您向它传递了错误类型的构造函数参数。

关于c++ - 为什么我可以使用 make_unique 创建带有衰减数组指针的 unique_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34117585/

相关文章:

c++ - 有效维护略有不同(日志记录/非日志记录)的功能

c++ - 如何以简单的方式声明可变参数模板类的类型

c++ - C++17 之前的函数交错

c++ - 必须在 std::vector<std::thread> 中加入 std::thread 两次以避免从线程 dtor 终止

c++ - 如何获得比较两个 vector 对的子集?

c++ - 数组是什么类型?

c++ - 为什么 enable_if 的行为不如预期?

c++ - 使用 pthread_cond_signal 优雅地终止线程被证明是有问题的

c++ - CCfits 库演示代码不起作用

python - 编译Boost.Python代码报错: library not found for -lpython3. 6m