How to achieve python-like behavior with references in c++?

Viewed 127

In python, if I do:

a = []
b = a 
a.append(1)
b[0] == 1 

This works fine, as both a and b are pointing to the underlying object on the heap.

What would be the equivalent C++ code?

3 Answers

What would be the equivalent C++ code?

Following would be a decent translation:

std::vector<int> a;
auto& b = a;
a.push_back(1);
b[0] == 1;

The key to having reference semantics is to use a reference variable.

You can use shared_ptr: all copies are operate single instance of data. And you will be able to reassign new instance for operations (it's better than reference).

While the reference should be preferred when possible due to their simplicity, just to be complete, here a solution with shared pointer:

#include <iostream>
#include <memory>
#include <vector>

int main()
{
 auto a = std::make_shared<std::vector<int>>();
 auto b = a;
 a->push_back(1);

 std::cout << "This is One: " << (*b)[0] << "\n";
}

Yeah, c++ can look really bad compared to python for trivial things... At least we have "auto" now to avoid repeatedly having to type: std::shared_ptr<std::vector<int>> in this case.

Related