How to create an array with a reference element in C ++?

I have a Foo and Logger class:

class Logger{/* something goes here */};
class Foo{
  Foo(Logger& logger);
  Logger& logger;
}

Foo::Foo(Logger& logger) : logger(logger)
{}

Now I want to create an array of objects of the Foo class, where all links Foo::loggermust point to the same object Logger. I tried something like (I need both stack distribution and heaps):

Logger log (/* parameters */);
Foo objects [3] (log); // On stack
Foo* pObjects = new Foo [3] (log); // On heap

The problem is that both versions try to call the default constructor Foo(), which is not there. Also, as I understand it, it is impossible to change the link variable of the link. Therefore, a temporary call to the default constructor and subsequent initialization in a loop also do not help.

So: What is the right way to do this? Do I need to use pointers to an object Logger?

+5
source share
3 answers

logger a Singleton, . http://en.wikipedia.org/wiki/Singleton_pattern

Foo .

class Logger
{
    public:
        static Logger& getInstance()
        {
            static Logger    instance;
            return instance;
        }

        public log(const std::string& txt) 
        {
            //do something
        }

    private:
        Logger() {}
        Logger(Logger const&);              // Don't Implement.
        void operator=(Logger const&); // Don't implement
 };

Foo :

 Logger::getInstance().log("test");

 Logger& logger = Logger::getInstance();
 logger.log("test");

( singleton @Loki Astari: ++ Singleton design pattern)

+2

. , ( )

:

Foo* pObjects[3];

for (int i = 0; i < 3; ++i) {
   pObjects[i] = new Foo(log);
}
+5

, ++ 11:

class Logger{/* something goes here */};
class Foo{
public:
  Foo(Logger& logger);
private:
  Logger& logger;
};

Foo::Foo(Logger& logger) : logger(logger)
{}


EDIT: ++ 11 vector , :
#include <vector>
class Logger{/* something goes here */};
class Foo{
public:
  Foo(Logger& logger) : logger(logger) {}
private:
  Logger& logger;
};

int main () {
  Logger log;
  std::vector<Foo>(3, log);
}

, vector ++ 03. ++ 03 - Foo::operator=. ++ 11 Foo::Foo(const Foo&).

+2

All Articles