C++ Representing Optional Objects
Asked Answered
D

2

6

I have a C++ project. I work on the project to teach myself about building a semi-realistic program in C++. It downloads content recursively from a website.

Each download has a URL for the content to download, as well as a URL for the referrer (or the URL of the page that the content was extracted from).

There is always a referrer unless it's the very first URL. I had been cheating and just treating the first URL as its own referrer. I recently changed the URL class to have a blank (or empty) representation. This feels like a hack.

Is there a way to represent optional objects in C++ without:

  • Using pointers?
  • Wasting space for the invalid object?
  • or Making a "blank" version of the object?
Declared answered 7/6, 2013 at 12:45 Comment(1)
W\O: Using pointers? IMHO not.Genny
F
5

You could use boost::optional. boost is well-respected 3rd party library; often regarded as a prototype for new stl functions: See Ralph's answer std::optional is available with new C++.

See http://www.boost.org/

Fuller answered 7/6, 2013 at 12:48 Comment(3)
I originally posted that as a comment, but won't that waste space for the "blank" version? Not that I think it is a serious problem, but it is one of the specific requirements of the question.Sin
No. boost::optional uses a pointer, set to NULL as appropriate, in its implementation. Don't know how std::optional works.Fuller
@Fuller I'm just trying to avoid reinventing established conventions. I used unique_ptr but decided it made the code look lopsided. I felt it wasn't explicitly saying "this field is optional". Instead it looked like a memory management technique.Declared
W
5

Use the std::optional template, if you have a C++14 compiler. If not you can use boost::optional or std::unique_ptr. You cannot avoid both using pointers and wasting space for the invalid object. std::optional will contain the optional object, std::unique_ptr will obviously point to it.

Wineshop answered 7/6, 2013 at 12:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.