Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 关于auto_ptr的一个问题 模板 运算符自动\u ptr\u ref()抛出(){ 返回auto_ptr_ref(release()); }_C++_Templates_Standard Library - Fatal编程技术网

C++ 关于auto_ptr的一个问题 模板 运算符自动\u ptr\u ref()抛出(){ 返回auto_ptr_ref(release()); }

C++ 关于auto_ptr的一个问题 模板 运算符自动\u ptr\u ref()抛出(){ 返回auto_ptr_ref(release()); },c++,templates,standard-library,C++,Templates,Standard Library,它是在标准库中实现类auto_ptr的一部分 这意味着什么 为什么在“操作符”和“()”之间有一个“auto_ptr_ref”?这是一个正在运行的转换操作符,从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”?

这是一个正在运行的转换操作符,从auto_ptr转换为auto_ptr_ref。

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

template<class Y>

operator auto_ptr_ref<Y>() throw() {

   return auto_ptr_ref<Y>(release());
}
但如果我们将其更改为
A(A&A)
,我们将无法从按值/临时A构建:这些不能绑定到对非成本的引用:

A(A const& a) { 
    /* oops, a is const, we can't steal something from it! */ 
}
auto_ptr和我们的A类使用了一种技巧,即非常量成员函数仍然可以通过临时值/值A调用。也就是说,我们还可以写:

A(A &a) { 

}

...
A a = A(); // fail, because A &a = A() doesn't work

但这是可行的,我们当然不想为此烦恼。我们希望它只用于指定一个
a()
或一个按值返回
a
的函数的返回值。所以auto_ptr和我们的A类使用的是一个转换运算符,它自动计算出当A转换为B时,我们可以使用我们临时创建的B构造一个A实例

强制转换运算符是转换运算符的同义词。
A(A &a) { 

}

...
A a = A(); // fail, because A &a = A() doesn't work
struct A {
    ...
    B get_b() { return B(*this); } 
    ...
};

...
A a = A().get_b();