How to create an array of smart pointers?

1.8k views Asked by At

I have created a class, which reference some members as smart pointers, I want to create an array of this class but I get different types of errors

class ConnectionType : public SimpleRefCount<ConnectionType> {
public:
  Ptr<Socket> txMstrSocPtr; /// Pointer to Master tx socket
  Ptr<Socket> rxMstrSocPtr; /// Pointer to Master rx socket
  Ptr<Socket> txSlavSocPtr; /// Pointer to Slave tx socket
  Ptr<Socket> rxSlavSocPtr; /// Pointer to Slave rx socket

  //ConnectionType();
  //~ConnectionType();

  void rxMstrCallBack(Ptr<Socket> socket);
  void rxSlavCallBack(Ptr<Socket> socket);
};

Ptr<ConnectionType> ConnectionArray[NUMBER_OF_CONNECTIONS] = CreateObject<ConnectionType>();

it gives me errors Error 1 error C2075: 'ConnectionArray' : array initialization needs curly braces
2 IntelliSense: initialization with '{...}' expected for aggregate object

1

There are 1 answers

3
bpw1621 On

If you know the number of connections that will be returned by CreateObject at compile-time (i.e., NUMBER_OF_CONNECTIONS is a compile-time constant) you could use std::array< Ptr< ConnectionType >, NUMBER_OF_CONNECTIONS >. std::array models a raw array most closely of the standard containers and is to be prefer to raw arrays when writing modern C++. If NUMBER_OF_CONNECTIONS has a size that is determined at run-time you can use std::vector< Ptr< ConnectionType > >. So change to either

#include <array>
...
std::array< Ptr< ConnectionType >, NUMBER_OF_CONNECTIONS > ConnectionArray{ CreateObject< ConnectionType >() };

or

#include <vector>
...
std::vector< Ptr< ConnectionType > > ConnectionArray{ CreateObject< ConnectionType >() };

Also, if you weren't already aware, C++11 added support for three flavors of standard smart pointers: unique_ptr, shared_ptr and weak_ptr (they differ in their ownership semantics) which you might prefer to use over your own homemade smart pointers if they meet your needs and you are able to use a compiler that implements them.