【问题标题】:A question about auto_ptr关于auto_ptr的一个问题
【发布时间】:2009-02-01 17:09:57
【问题描述】:
template<class Y>

operator auto_ptr_ref<Y>() throw() {

   return auto_ptr_ref<Y>(release());
}

它是标准库中类 auto_ptr 实现的一部分。

这是什么意思?

为什么“operator”和“()”之间有一个“auto_ptr_ref”?

【问题讨论】:

    标签: c++ templates standard-library


    【解决方案1】:

    我会告诉你为什么转换运算符恰好在那里。好吧,看看这个例子:

    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 &amp;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 实例。

    【讨论】:

      【解决方案2】:

      这就是转换运算符的作用,从 auto_ptr 转换为 auto_ptr_ref

      【讨论】:

      • 强制转换运算符是转换运算符的同义词。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多