Skip to content

Instantly share code, notes, and snippets.

@mattmcd
Created March 25, 2013 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmcd/5240193 to your computer and use it in GitHub Desktop.
Save mattmcd/5240193 to your computer and use it in GitHub Desktop.
Examples of the different uses of const in C++
#include <iostream>
#include <vector>
#include <string>
#include <memory>
typedef std::vector<std::string> str_vec;
void print(str_vec const list)
{
for ( auto el : list ) std::cout << el << std::endl;
}
int main()
{
// Immutable list of elements on the stack
const str_vec names = {"one", "two"};
// *(names.end() - 1) = "three"; // Compile error: immutable elements
// names.push_back("three"); // Compile error: immutable list
print(names);
// Constant pointer to list of mutable elements
// Scala: val name_ptr = Array("four", "five")
const auto name_ptr = std::unique_ptr<str_vec>(new str_vec {"four","five"});
(*name_ptr)[1] = "six"; // OK
print(*name_ptr);
// Mutable pointer to list of immutable elements
// Scala: var name_ptr2 = List("seven", "eight")
auto name_ptr2 = std::unique_ptr<const str_vec>(new str_vec {"seven","eight"});
// (*name_ptr2)[1] = "nine"; // Compile error: const elements
print(*name_ptr2);
// Another list of immutable elements
auto name_ptr3 = std::unique_ptr<const str_vec>(new str_vec {"nine","ten"});
// Can reassign name_ptr2
name_ptr2 = std::move(name_ptr3); // OK
print( *name_ptr2 );
// print( *name_ptr3 ); // Runtime error: move deletes name_ptr3
// Immutable pointer to list of immutable elements
// Scala: val name_ptr4 = List("eleven")
const auto name_ptr4 = std::unique_ptr<const str_vec>(new str_vec {"eleven"});
// name_ptr4 = std::move(name_ptr2); // Compile error: const pointer
print( *name_ptr4 );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment