Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) BOOST_FOREACH Example1

 

BOOST_FOREACH Example1 is a BOOST_FOREACH example.

 

 

 

 

 

Technical facts

 

Application type(s)

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: CppBOOST_FOREACH Example1.pro

 

#-------------------------------------------------
#
# Project created by QtCreator 2012-01-26T06:03:38
#
#-------------------------------------------------

QT       += core

QT       -= gui

TARGET = CppBOOST_FOREACH Example1
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app


SOURCES += main.cpp

 

 

 

 

 

main.cpp

 

#include <iostream>
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>

const std::vector<std::string> f()
{
  std::vector<std::string> v;
  for (int i=0; i!=1000; ++i) { v.push_back( boost::lexical_cast<std::string>(i)); }
  return v;
}


//GOOD: Compiler warning
//const std::vector<std::string>& f_ref()
//{
//  std::vector<std::string> v;
//  for (int i=0; i!=1000; ++i) { v.push_back( boost::lexical_cast<std::string>(i)); }
//  return v;
//}

const std::vector<std::string> g()
{
  static std::vector<std::string> v;
  if (!v.empty()) return v;
  for (int i=0; i!=1000; ++i) { v.push_back( boost::lexical_cast<std::string>(i)); }
  return v;
}

const std::vector<std::string>& g_ref()
{
  static std::vector<std::string> v;
  if (!v.empty()) return v;
  for (int i=0; i!=1000; ++i) { v.push_back( boost::lexical_cast<std::string>(i)); }
  return v;
}

int main()
{
  std::string t;

  //BAD: Compiles and crashes program
  //std::clog << __func__ << '\n'; BOOST_FOREACH(const std::string  s, f()) { t+=s; }

  //BAD: Compiles and crashes program
  //std::clog << __func__ << '\n'; BOOST_FOREACH(const std::string& s, f()) { t+=s; }

  //GOOD: Compiler warning about f_ref
  //std::clog << __func__ << '\n'; BOOST_FOREACH(const std::string  s, f_ref()) { t+=s; }

  //GOOD: Compiler warning about f_ref
  //std::clog << __func__ << '\n'; BOOST_FOREACH(const std::string& s, f_ref()) { t+=s; }

  //BAD: Compiles and crashes program
  //std::clog << __func__ << '\n'; BOOST_FOREACH(const std::string  s, g()) { t+=s; }

  //BAD: Compiles and crashes program
  //std::clog << __func__ << '\n'; BOOST_FOREACH(const std::string& s, g()) { t+=s; }

  //GOOD: Works
  std::clog << __func__ << '\n'; BOOST_FOREACH(const std::string  s, g_ref()) { t+=s; }

  //BEST: Works without making a copy of each std::string
  std::clog << __func__ << '\n'; BOOST_FOREACH(const std::string& s, g_ref()) { t+=s; }

std::clog << t;
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml