gpt4 book ai didi

c++ - 空结构背后的目的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:22:26 28 4
gpt4 key购买 nike

来自 C++ 标准库的 auto_ptr 声明

namespace std {

template <class Y> struct auto_ptr_ref {};


template <class X>
class auto_ptr {
public:
typedef X element_type;

// 20.4.5.1 construct/copy/destroy:
explicit auto_ptr(X* p =0) throw();
auto_ptr(auto_ptr&) throw();
template <class Y> auto_ptr(auto_ptr<Y>&) throw();

auto_ptr& operator=(auto_ptr&) throw();
template <class Y> auto_ptr& operator=(auto_ptr<Y>&) throw();
auto_ptr& operator=(auto_ptr_ref<X>) throw();

~auto_ptr() throw();

// 20.4.5.2 members:
X& operator*() const throw();
X* operator->() const throw();
X* get() const throw();
X* release() throw();
void reset(X* p =0) throw();

// 20.4.5.3 conversions:
auto_ptr(auto_ptr_ref<X>) throw();
template <class Y> operator auto_ptr_ref<Y>() throw();
template <class Y> operator auto_ptr<Y>() throw();
};

我不明白这部分的目的:

template <class Y> struct auto_ptr_ref {};

没有声明任何变量,这些如何有效:

auto_ptr&                      operator=(auto_ptr_ref<X>) throw();

还有这些:

auto_ptr(auto_ptr_ref<X>) throw();
template <class Y> operator auto_ptr_ref<Y>() throw();

编辑: 而且(我刚刚注意到)我不明白最后两行如何使用“运算符”。语法不是类似于“return-type operatoroperand;”,返回类型在哪里?操作数?

最佳答案

Google 搜索“auto_ptr_ref”会显示 this detailed explanation .

我不太明白这个解释,但看起来是为了以下内容。如果没有这个技巧,您可以将 auto_ptr 传递给一个函数,该函数将获得对象的所有权并将您的变量分配给空指针。使用上面的额外类技巧,在这种情况下你会得到一个编译错误。

关于c++ - 空结构背后的目的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3316514/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com