clang,返回带有类型转换的std::unique_ptr
clang, returning std::unique_ptr with type conversion
这是我的代码:
#include <memory>
struct A{};
struct B: A {};
std::unique_ptr<A> test()
{
auto p = std::make_unique<B>();
return p;
}
int main(int argc, char **argv)
{
test();
return 0;
}
它没有在clang上编译错误:
main.cpp:11:12: error: no viable conversion from returned value of type 'unique_ptr<B, default_delete<B>>' to function return type 'unique_ptr<A, default_delete<A>>'
然而,根据这个(同样的情况)它应该。我误解什么了吗?
我的命令行(clang ver 3.7):
clang++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
这是一个clang bug。来自[class.copy]:
当满足省略复制/移动操作的条件,但不满足异常声明的条件时,并且当
return
语句中的表达式为(可能带括号)id表达式,用于命名在正文或最里面的封闭函数或lambda表达式的参数声明子句,重载解析为副本选择构造函数首先执行,就好像对象是由rvalue指定的一样。
省略的条件没有得到满足(因为p
的类型与函数的返回类型不同),但代码应该仍然有效,因为重载解析应该像p
是右值一样进行。
也就是说,你确实希望移动省略发生,所以在这种情况下不要使用auto
:
std::unique_ptr<A> test()
{
std::unique_ptr<A> p = std::unique_ptr<B>();
return p;
}
clang接受此代码,并且移动省略将发生。双赢。
您需要从unique_ptr中move
。以下代码在CLang和gcc上编译:
#include <memory>
struct A{};
struct B: A {};
std::unique_ptr<A> test()
{
auto p = std::make_unique<B>();
return std::move(p);
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 为什么 std::unique 不调用 std::sort?
- 我对 std::unique(算法)C++有问题
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++ std::unique并没有显示我对它的期望
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 为什么 [std::unique] 不能应用于 [std::multiset]?
- 使用 std::unique 和 vector.erase 删除除最后一次出现的重复元素之外的所有元素
- 是否可以在 std::unique<T[ ]> 上应用 std::sort?
- std::unique 是否有大小限制
- 从 std::unique 返回的迭代器的用法
- 使 std::unique<T> 与 std::unique<const T, CustomDeleterType 兼容>
- Std::list.unique()应该使迭代器无效
- 无法使用初始化器列表构造 vector<std::unique<...>>
- 从自定义对象- std:unique的向量中消除重复项会导致崩溃
- 我能保证std::unique将保留第一个元素吗?
- 在 std::vector<std::unordered_set上使用 std::unique(<T>>