简体   繁体   中英

Returning a reference to a forward-declared type (C++)

I have a class method that returns a reference to something. When I use this method, if I only have a forward declaration of that something, I can only compile if I assign the output of the method. I really don't understand why...

Here's a simplified example:

ClassA.h:

//Forward declare
class ClassB;

class ClassA
{
public:
    ClassA(void);
    ~ClassA(void);

    ClassB& Func();
};

ClassA.cpp:

#include "ClassA.h"

#include "ClassB.h"

ClassA::ClassA(void)
{}

ClassA::~ClassA(void)
{}

static ClassB c;

ClassB& ClassA::Func()
{
    return c;
}

ClassB.h:

#pragma once
class ClassB
{
public:
    ClassB(void) {};
    ~ClassB(void) {};
};

Now, if I call ClassA::Func without assigning the return value (while only having a forward declaration of ClassB ), it will not compile:

main.cpp:

#include "ClassA.h"

int main(void)
{
    ClassA a;

    a.Func(); //error C2027: use of undefined type 'ClassB'

    return 0;
}

If I use this line instead, it works: ClassB& b = a.Func();

What's happening here? Why would the compiler need to know the size of ClassB or what its methods are when the return value is not assigned anywhere?

I'm compiling this with VisualStudio 2010 SP1.

Looks like a "limitation" of the compiler, the MSDN page for C2027 says :

It is possible to declare a pointer to a declared but undefined type. But Visual C++ does not allow a reference to an undefined type.

The following sample generates C2027.

And gives this example :

class A;
A& CreateA();

class B;
B* CreateB();

int main() {
   CreateA();   // C2027
   CreateB();   // OK
}

So both of your examples are supposed to generate a C2027, I'm not sure why the second does not (that is, without more documentation, it is a bug)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM