引用指针后面的值

时间:2017-03-18 12:28:27

标签: c++ pointers reference

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

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();

1 个答案:

答案 0 :(得分:2)

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

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

请改为尝试:

auto& fs = concrete_call->GetStreamAttachementDestination_AsReference();