Skip to content

Instantly share code, notes, and snippets.

@carlos-urena
Last active March 20, 2023 10:32
Show Gist options
  • Save carlos-urena/f5bebecce73aebe24f1a27f4c4275e28 to your computer and use it in GitHub Desktop.
Save carlos-urena/f5bebecce73aebe24f1a27f4c4275e28 to your computer and use it in GitHub Desktop.
Testing how C++11 initializes native arrays and std vectors
// here it is shown how implicit std vector initialization uses copy
// constructor to replicate a single object when populating the vector
// also cheking the use of 'std::span', 'std::vector' and 'std::array'
// as function parameters
//
// Compile with: -std=c++20
#include <iostream>
#include <vector>
#include <array>
#include <string>
#include <span>
using namespace std ;
class A
{
public:
A()
{
x = 0 ;
cout << "constructor (), x == " << x << endl ;
}
A( int ix )
{
x = ix ;
cout << "constructor (int), x == " << x << endl ;
}
A( const A & a )
{
x = a.get_x() ;
cout << "copy constructor, x == " << x << endl ;
}
int get_x() const { return x ; }
private:
int x ;
} ;
void print_array( const std::vector<A> & v )
{
cout << "As vector: { " ;
for( int i = 0 ; i < v.size() ; i++ )
{
cout << v[i].get_x() ;
if (i < v.size()-1 ) cout << ", " ;
}
cout << " }" << endl << endl ;
}
void print_array( const std::span<const A> v )
{
cout << "As span: { " ;
for( int i = 0 ; i < v.size() ; i++ )
{
cout << v[i].get_x() ;
if (i < v.size()-1 ) cout << ", " ;
}
cout << " }" << endl << endl ;
}
template<class T, int N>
void print_array( const std::array<T,N> & v )
{
cout << "As array<T " << N << ">: { " ;
for( int i = 0 ; i < v.size() ; i++ )
{
cout << v[i].get_x() ;
if (i < v.size()-1 ) cout << ", " ;
}
cout << " }" << endl << endl ;
}
int main()
{
const int N = 4 ;
cout << "using native array initialization" << endl ;
const A a1[N] = {1,2,3,4} ;
print_array(a1);
cout << "using 'std::vector' initialization" << endl ;
const std::vector<A> a2 = {1,2,3,4} ;
print_array(a2);
cout << "using 'std::vector' (initialized with a single replicated value)" << endl ;
const std::vector<A> a3(N,123) ;
print_array(a3);
cout << "using 'std::array'" << endl ;
const std::array<A,N> a4 = {1,2,3,4} ;
print_array(a4);
// using an initializer list, it is converted to a vector
cout << "using an initializer lists" << endl ;
print_array( {1,2,3,4} );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment