构造函数采用auto_ptr
Constructor taking an auto_ptr
我想用一个构造函数编写一个C++类,该构造函数将auto_ptr
作为其参数,以便我可以将类实例从 auto_ptr
s 初始化到另一个实例:
#include <memory>
class A
{
public:
A() {}
A(std::auto_ptr<A> other) {}
};
std::auto_ptr<A> create()
{
return std::auto_ptr<A>(new A());
}
void foo()
{
A x = create();
// A y ( create() ); // works
}
在 gcc 4.6 上使用 g++ -c test.cpp
编译此代码会产生以下错误消息:
test.cpp: In function ‘void foo()’:
test.cpp:17:16: error: no matching function for call to ‘std::auto_ptr<A>::auto_ptr(std::auto_ptr<A>)’
test.cpp:17:16: note: candidates are:
/usr/include/c++/4.6/backward/auto_ptr.h:260:7: note: std::auto_ptr<_Tp>::auto_ptr(std::auto_ptr_ref<_Tp>) [with _Tp = A]
/usr/include/c++/4.6/backward/auto_ptr.h:260:7: note: no known conversion for argument 1 from ‘std::auto_ptr<A>’ to ‘std::auto_ptr_ref<A>’
/usr/include/c++/4.6/backward/auto_ptr.h:125:9: note: std::auto_ptr<_Tp>::auto_ptr(std::auto_ptr<_Tp1>&) [with _Tp1 = A, _Tp = A]
/usr/include/c++/4.6/backward/auto_ptr.h:125:9: note: no known conversion for argument 1 from ‘std::auto_ptr<A>’ to ‘std::auto_ptr<A>&’
/usr/include/c++/4.6/backward/auto_ptr.h:112:7: note: std::auto_ptr<_Tp>::auto_ptr(std::auto_ptr<_Tp>&) [with _Tp = A, std::auto_ptr<_Tp> = std::auto_ptr<A>]
/usr/include/c++/4.6/backward/auto_ptr.h:112:7: note: no known conversion for argument 1 from ‘std::auto_ptr<A>’ to ‘std::auto_ptr<A>&’
test.cpp:7:3: error: initializing argument 1 of ‘A::A(std::auto_ptr<A>)’
但是,如果我使用语法A y (create());
来创建我的对象,它会起作用。
我想知道为什么会发生这种情况,以及我是否可以做些什么来解决这个问题。
编辑:我还要指出,如果我将构造函数签名更改为
A(const std::auto_ptr<A>& other) {}
然后一切都运行良好,但是这不拥有auto_ptr
,因此没有我想要的语义。
编辑2:如果我对赋值运算符做同样的事情,即
A& operator=( std::auto_ptr<A> other) {}
那我可以做
A x;
x = create();
为什么?
只允许进行一次用户定义的隐式转换。从另一个auto_ptr
构造一个已经涉及通过辅助auto_ptr_ref
类的隐式转换,因此你不能从auto_ptr
隐式构造自己的类。
通过使用直接初始化,其中一个转换是显式的,并且只保留一个隐式用户定义的转换,这很好。
要"解决"缺少隐式转换的问题,您可以修改构造函数以通过(非常量)引用获取auto_ptr
,或者将所有内容迁移到 unique_ptr
s。
使用:
A(std::auto_ptr<A>& other)
// ^ Note the reference!
{
// Assign interned auto_ptr member here, which you definitely should have
}
相关文章:
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- CLANG 编译器 说:变量"PTR"可能未初始化
- 如何在自定义类中启用'auto loops'?
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 擦除许多矢量元素,同时使用'auto'
- 考虑到其他好处,关键字'auto'真的有助于简化调试C++吗?
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- 推理类型如何工作"auto"和按引用调用?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 'auto *x = new some_struct{};"是一个未初始化的变量?
- 为什么 std::gcd/lcm 返回 std::common_type_t<M, N> 而不是 auto?
- 将函数参数类型声明为 auto