quicktype icon indicating copy to clipboard operation
quicktype copied to clipboard

[BUG]: Getters for optional values in C++ should return a const reference

Open flounderpinto opened this issue 9 months ago • 0 comments

Currently, the get_xyz() methods return a copy of optional values. Something like: boost::optional<std::vector<Coordinate>> get_coordinates() const { return coordinates; } Which makes this code not behave as expected: for (auto coordinate: test.get_coordinates()) std::cout << "latitude" << coordinate.get_latitude() << std::endl; Required getters work as expected: 'const std::vector<Coordinate> & get_coordinates_required() const { return coordinates_required; }'

Issue Type

This is an issue with quicktype C++ code generation.

Context (Environment, Version, Language)

Input Format: Json Scheam Output Language: C++

CLI, npm, or app.quicktype.io: Version: Current

Description

Returning a copy of the boost::optional means that user's can't iterate through the vector as they might initially expect, leading to bugs. It's also presumably less efficient that returning a const reference to the underlying object.

Input Data

{ { "$schema": "http://json-schema.org/draft-06/schema#", "$ref": "#/definitions/foo", "definitions": { "coordinate": { "type": "object", "required": [ "latitude", "longitude" ], "additionalProperties": false, "properties": { "latitude": { "type": "number" }, "longitude": { "type": "number" } } }, "coordinates": { "type": "array", "items": { "$ref": "#/definitions/coordinate" } }, "foo": { "type": "object", "required": [ "coordinates-required" ], "additionalProperties": false, "properties": { "coordinates": { "$ref": "#/definitions/coordinates" }, "coordinates-required": { "$ref": "#/definitions/coordinates" }, "bar" : { "type": "number" } } } } }

Expected Behaviour / Output

const boost::optional<std::vector<Coordinate>>& get_coordinates() const { return coordinates; }

Current Behaviour / Output

boost::optional<std::vector<Coordinate>> get_coordinates() const { return coordinates; }

Steps to Reproduce

Using above schema; quicktype --lang c++ -s schema --out ./test.h ./test.schema.json (or insert into app.quicktype.io)

Possible Solution

flounderpinto avatar Jan 14 '25 19:01 flounderpinto