引用指针后面的值

reference to a value behind a pointer

本文关键字:指针 引用      更新时间:2023-10-16

我想要对指针后面的值的引用。

class UnicastCall {
protected:
    std::fstream *m_stream_attachement_destination_;
...
public:
auto GetStreamAttachementDestination_AsPointer() -> decltype(m_stream_attachement_destination_)
    { return m_stream_attachement_destination_; } //THIS WORKS
auto GetStreamAttachementDestination_AsReference() -> decltype(*m_stream_attachement_destination_) &
    { return *m_stream_attachement_destination_; } //IS THIS CORRECT?
....
};

但是我得到一个错误。

error: use of deleted function 'std::basic_fstream<_CharT, _Traits>::basic_fstream(const std::basic_fstream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]'
 auto fs = concrete_call->GetStreamAttachementDestination_AsReference();

您正在尝试复制std::fstream,这是不允许的。

错误不在您的类中,而是在呼叫站点。 auto fs = ... 不创建引用,但尝试调用复制构造函数;auto只能代替std::fstream,不能代替&

试试这个:

auto& fs = concrete_call->GetStreamAttachementDestination_AsReference();