template<class Y>
operator auto_ptr_ref<Y>() throw() {
return auto_ptr_ref<Y>(release());
}
它是标准库中类 auto_ptr 实现的一部分。
这意味着什么?
为什么“运算符”和“()”之间有一个“auto_ptr_ref”?
template<class Y>
operator auto_ptr_ref<Y>() throw() {
return auto_ptr_ref<Y>(release());
}
它是标准库中类 auto_ptr 实现的一部分。
这意味着什么?
为什么“运算符”和“()”之间有一个“auto_ptr_ref”?
我会告诉你为什么那个转换运算符碰巧在那里。好吧,看看这个例子:
struct A;
struct B {
explicit B(A&a):a(a){ }
A &a;
};
struct A {
A() { }
A(B b){ move_from(a); }
A(A &a) { move_from(a); }
operator B() { return B(*this); }
void move_from(A &a) {
std::cout << "A::A(@" << &b.a << ")" << std::endl;
}
};
int main() {
A a = A();
}
我们的类 A 有移动语义:在它的复制构造函数中,我们想从另一个实例中“窃取”一些东西。对于 auto_ptr,这是托管的指针,对我们来说,我们只是输出一条消息。重要的是我们不能使用通常的复制构造函数:
A(A const& a) {
/* oops, a is const, we can't steal something from it! */
}
但是,如果我们将其更改为A(A &a)
,我们将无法从按值/临时 A 构造:那些不能绑定到对非常量的引用:
A(A &a) {
}
...
A a = A(); // fail, because A &a = A() doesn't work
auto_ptr 和我们的 A 类使用仍然可以在临时/按值 A 上调用非常量成员函数的技巧。也就是说,我们也可以这样写:
struct A {
...
B get_b() { return B(*this); }
...
};
...
A a = A().get_b();
但这行得通,当然,我们不想为此烦恼。我们希望它只分配一个A()
或返回一个A
按值的函数的返回值。所以 auto_ptr 和我们的 A 类使用的是转换运算符,它会自动计算出当 A 转换为 B 时,我们可以使用我们临时创建的 B 构造一个 A 实例。
这就是转换运算符的作用,从 auto_ptr 转换为 auto_ptr_ref<Y>。