Creating a Vector with Class Storage using C++11 smart_pointers

/* Sometimes we need to construct several classes and then pass 
them somewhere to do something, but we don't have an abstract 
storage method. The unique_ptr can help */

// Example program
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Test {
 public:
  std::string m_val; 
  Test(const std::string & val) : m_val(val) {}
  ~Test() {}
  std::string getVal() const {return m_val;}
};

void printValues(std::vector<const Test*> & tests)
{
  for (auto & test : tests)
    std::cout << "Test.m_val: " << test->getVal() << std::endl;
}

int main()
{
  std::vector< std::unique_ptr<const Test> > tests;
  tests.emplace_back(new Test("test 1"));
  tests.emplace_back(new Test("test 2"));

  std::vector<const Test*> refs;
  for (auto & test : tests)
    refs.push_back(test.get());

  printValues(refs); 
} 
/* I don't know about you, but I think this is pretty elegant. We have 
clear communication of where storage is being kept. The unique_ptr will 
be cleaned up at the end of 'tests' scope (keeping in alignment with RAII), 
and the functions are user friendly in that they expect raw pointers and as 
such they work for a container class and for our immediate storage needs. */
Advertisements
Posted in C++

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s