views:

1045

answers:

4

I'm creating an interface wrapper for a class. The member within the class is a reference(to avoid copying the large structure). If I create a private constructor, what is the best way to initialize that reference to appease the compiler?

struct InterfaceWrapper {
    InterfaceWrapper( SomeHugeStructure& src ):m_internal(src){};
    int someElement(void) const { return m_internal.someElement; };
private:
    InterfaceWrapper(){}  // initialize m_internal
    SomeHugeStructure& m_internal;
};
+3  A: 

If you really need to construct the class without having an element, a reference is not the way to go.

If your only reason to use a reference is to avoid copying, I'd suggest using a pointer. You can simply take the address of the passed reference in you regular constructor, and initialize it to NULL in the private constructor. When the object's lifetime ends the pointer will be a dangling pointer, but the same is true for references...

Alternatively, have the public constructor take a smart pointer and use such a smart pointer as member too, if you're concerned about lifetimes.

And of course, cope with the pointer possibly being NULL in the remainder of the class' code. (but you had to cope with the member possible being a stub in the reference case too, so that's not really an issue)

Pieter
+1  A: 

What is the point of the private ctor? If m_internal is not referencing a valid object, how can it be useful?

Also the m_internal-> won't compile. That is pointer syntax, not ref.

Chris Morley
+2  A: 

If you are making the default ctor private to prevent anyone from using it, then just leave off the body:

private:
    InterfaceWrapper();
    SomeHugeStructure& m_internal;

The compiler will think it's defined elsewhere, and the linker won't mind that it's not unless someone tries to use it.

James Curran
If you define any other constructor the compiler does not automatically generate a default constructor. So in this case it could safely be removed from the code.
Martin York
+3  A: 

As others have mentioned, if your purpose is to prevent others from calling the default constructor, then you don't want to provide a body at all, and declaring it is unnecessary since you have another constructor and the compiler won't generate it for you.

If the purpose is to limit access to friends of the class, then you would probably be best having a pointer (prefereably a smart pointer) member, and setting it to NULL.

--

Also, I'm not sure why you made this a struct rather than a class. In general making something a struct makes sense when you're exposing data members as public, similar to C. In this case, it looks like you have a conventional class, in which case the C++ convention would be to make it a class.

JohnMcG