Menu
CoddyTech

Value Copies

Lesson 17 of 48 in Coddy's C++ for Lua Developers course.

In Lua, a table is a reference value: b = a makes two names for one table, and there is no built-in copy. A copy loop over ipairs creates a new outer table, but any nested tables are still shared, so it is only a shallow copy. Numbers and strings are immutable, so sharing them never matters. C++ containers are values: copying a std::vector or std::string copies every element into independent storage, and for a vector of vectors that includes every inner vector. Copying a raw pointer is different: it still shares the object it points to and says nothing about who owns it.

Lua

local original = {{1}}
local copy = {}
for i, v in ipairs(original) do
  copy[i] = v
end
copy[1][2] = 2
copy[2] = {9}
print(#original)
print(#original[1])

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>

int main(){
std::vector<std::vector<int>> original{{1}};
auto copy=original;
copy[0].push_back(2);
copy.push_back({9});
std::cout<<original.size()<<" "<<original[0].size()<<"\n";
std::cout<<copy.size()<<" "<<copy[0].size()<<"\n";
}

When porting, a plain C++ copy already gives you what a Lua deep copy function would. Pass by reference when you want to avoid that cost, not to get sharing for free.

challenge icon

Challenge

Easy

Input: integers. Return a copy with its first element replaced by 99; do not change the original. Driver prints original then copy, using empty for an empty vector.

Implement the declared API in exercise.hpp and exercise.cpp. Both files are editable; preserve the public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.

Try it yourself

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);std::vector<int> v;int n;while(in>>n)v.push_back(n);auto b=changed_copy(v);for(const auto* p:{&v,&b}){if(p->empty())std::cout<<"empty";for(size_t i=0;i<p->size();++i){if(i)std::cout<<" ";std::cout<<(*p)[i];}std::cout<<"\n";}
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C++ for Lua Developers

Practice on your own: Online C++ compiler