struct forward declaration fails compile

2019-04-20 00:02发布

问题:

I have the following code, but the compiler says sender_wrapper is undefined, even though I forward declared it. Can I not do a forward declare of a struct? (compiled with VS2003)

struct send_wrapper;

struct IPSend
{
    IPSend::IPSend(const send_wrapper& sender) : _sender(sender) {}

    void IPSend::operator()(const std::string& msg)
    {           
        if (!msg.empty())
            _sender.send(msg);
    }

    send_wrapper _sender; //error C2079: 'IPSend::_sender' uses undefined struct 'send_wrapper'

};

struct send_wrapper 
{
std::auto_ptr<tcp_server> server;

};

回答1:

Forward declarations of types can only be used to resolve declarations involving pointers and references to that type.

Before the type has been fully defined, the compiler does not know anything about the type; e.g. what members it has, or how big it is. Therefore, you cannot use it as a by-value member of your struct, because the compiler wouldn't know how big to make it, or whether its constructors and destructor are public. On the other hand, you are free to do something like send_wrapper *_p_sender;, because pointers to structs are always the same size. But you still wouldn't be able to access its member functions, etc.



回答2:

Can I not do a forward declare of a struct?

Yes, but only for references and pointers to such a struct. Once you start poking inside it, such as accessing a member of it, you need the full declaration of the struct — otherwise, how's the compiler going to know your sender has a send() function?