How can you initialize a class using a reference element from a private constructor?

I am creating an interface wrapper for a class. An element inside a class is a reference (to avoid copying a large structure). If I create a private constructor, what is the best way to initialize this link 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
source share
4 answers

As already mentioned, if your goal is to prevent other users from referencing the default constructor, then you do not want to provide the body at all, and declare it unnecessary, since you have another constructor and the compiler will not create it for you.

, , , ( ) NULL.

-

, , , . , - , , C. , , ++ .

+4

, .

- , . NULL . , , ...

, , .

, , , , NULL . ( , ​​ , )

+4

ctor private, - , :

private:
    InterfaceWrapper();
    SomeHugeStructure& m_internal;

The compiler will assume that it is defined elsewhere, and the linker will not mind if he does not try to use it.

+2
source

What is the meaning of private ctor? If m_internal does not reference a valid object, how can it be useful?

Also m_internal-> will not compile. This is pointer syntax, not ref.

+1
source

Source: https://habr.com/ru/post/1699469/


All Articles