从函数返回Unique_ptr时出现Unique_ptr所有权错误
unique_ptr ownership error when return unique_ptr from function
我是新来的unique_ptr。一切都很好,直到我遇到一个函数返回一个新的unique_ptr。编译器似乎抱怨不止一个对象可能拥有unique_ptr。我不确定如何满足编译器的抱怨。如有任何帮助,不胜感激。
void Bar::Boo()
{
...
// m_Goals is of type std::unique_ptr<Goals>
auto x = m_Goals->Foo(); // error: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
//auto x = std::move( m_Goals->Foo() ); // same error
...
}
const std::unique_ptr<Goals> Goals::Foo()
{
std::unique_ptr<Goals> newGoals( new Goals() );
...
return newGoals;
// also tried "return std::move( newGoals )" based on http://stackoverflow.com/questions/4316727/returning-unique-ptr-from-functions
} // this function compiles
删除const
,当您返回const
值时,编译器将强制使用复制构造函数。通过const
值返回几乎没有任何意义,强烈建议不要返回。请参见const值返回的目的?查看更多信息。
相关文章:
- 为什么 std::unique 不调用 std::sort?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 生成"unique"矩阵
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 我对 std::unique(算法)C++有问题
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++中的指针否定 (!ptr == NULL)
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误