216 questions
Best practices
0
votes
8
replies
194
views
Should I use std::move when returning a local std::string as std::optional<std::string>?
My confusion is about the return statement inside readFileContents:
The function returns std::optional<std::string>, but the local variable is a std::string.
NRVO doesn’t apply here because ...
Best practices
0
votes
7
replies
177
views
One-line call to std::optional::emplace only if it has no value
In the same spirit than the creation of an instance in a std::map when calling operator[] , I would like to emplace (direclty in the expression) in an std::optional only if has_value() is false. In ...
2
votes
2
answers
304
views
Is there a possibility that sizeof(std::optional<T>) == sizeof(T)?
Is there a possibility, where sizeof(T) is the same as sizeof(std::optional<T>)?
I can imagine that nullptr would signal a "disengaged" std::optional<T*> but even that might not ...
-2
votes
2
answers
230
views
Optional const by-reference argument in C++
In a C++ program, I have an API function with the following signature:
Foo const & GetFoo() const;
The Foo class doesn’t allow copying or moving of instances. The API can’t easily be changed.
Now ...
1
vote
1
answer
131
views
I can't get an optional with (cond) ? value : nullopt ... what should I write instead?
Suppose I'm implementing the function returning an std::optional<T>. In that function, I compute some condition, and then want to return either a value, or a nullopt. I can do it like so:
std::...
15
votes
1
answer
744
views
Is implicit conversion to std::optional guaranteed to use move constructor?
The following code block illustrates a difference between returning a std::optional via an implicit conversion (i.e. fn) vs. an explicit construction (i.e. fn2). Specifically, the implicit conversion ...
5
votes
1
answer
177
views
range-based for-loop in C++ over std::optional<Container> does not work
Let me start with a C++ code that simplifies my issues I faced in the actual code base. I compiled it with --std=c++20 and --std=c++17. The first for-loop below was okay; the second for-loop, which ...
3
votes
0
answers
96
views
inheriting "operator =" from std::optional<T> (as a parent class) fails when T is native type
I'm wrapping std::optional<T> to add a few IMHO useful functions of my own, and I noticed that my code kept failing when T is native.
When assigning a variable of my wrapped-optional type to a ...
3
votes
3
answers
201
views
Correct way of inserting std::optional<T> into std::vector<T>
I have a class T, it looks like this:
class T {
uint64_t id;
std::string description;
char status;
uint64_t createdAt;
uint64_t updatedAt;
T(uint64_t c_id, std::string_view c_description, ...
1
vote
1
answer
144
views
`std::shared_ptr` vs `std::optional` for thread safe queue
In "C++ Concurrency in action" from Anthony Williams (2012) there is a thread safe queue implemented by storing std::shared_ptr<T> like so
template<typename T>
class ...
2
votes
2
answers
140
views
Return std::optional<T> where T's constructor is private
I still do not understand the behavior of std::optional in the following code:
class A
{
public:
// A(int x, int y) : x(x), y(y) {} // always compiles
private:
A(int x, int y) : x(x), y(y) {} //...
0
votes
2
answers
205
views
Why can't I assign an std::optional of std::lock_guard?
Why can't I declare an optional std::lock_guard and then assign it later? The same thing with an optional string works just fine.
This works:
std::mutex m;
std::optional<std::lock_guard<std::...
3
votes
2
answers
137
views
Function template call: type deduction and empty brace-enclosed initializer list
Consider the following function template calls:
#include <optional>
template <class T = int>
void f(std::optional<T>);
int main() {
f(1); // (1)
f({}); // (2)
}
The first ...
2
votes
1
answer
147
views
Casting std::optional inferior type
If I have an std::optional<T> then how can I transparently cast it to a std::optional<U> given that T and U are compatible types and preserving std::nullopt?
That is, if the initial std::...
1
vote
1
answer
200
views
Undefined class while using __declspec(dllexport) since Visual Studio 17.2
The following code compiles well for Visual Studio < 17.2:
#include <optional>
#include <map>
class __declspec(dllexport) A {
using M = std::map<int, A>;
std::optional<...
8
votes
3
answers
4k
views
When and why should I use std::monostate instead of std::optional with an std::variant?
Let's say I am writing a class that passes a std::variant<A,B> to another class.
While I design the class, I decide I'd like to keep a copy of the last thing that was passed to that other class. ...
15
votes
2
answers
1k
views
Can I have a std::optional<T> if T is neither constructible nor copyable nor movable?
The only requirement to type parameter of std::optional<T> class template mentioned in [optional.optional.general] p3 is that type T is Destructible.
Suppose I have a very restrictive class ...
8
votes
6
answers
2k
views
C++ equivalent of Javascript's '?.' operator for optional-chaining?
In Javascript, if I have a potentially null object obj, which, if not null, will have a field x - I can write obj?.x. This is called "optional chaining" or "safe navigation": If ...
0
votes
0
answers
43
views
OpenCV C++ Temporary RValue Class Reference Invalidated by std::optional member?
I believe the source of this is actually some C++ craziness, specifically with std::optional, but the context came from OpenCV. OpenCV has a datastructure, cv::Mat, and some variants (for gpu, etc). ...
-5
votes
2
answers
442
views
Why `emplace()` without arguments returns 0? [duplicate]
Below is the example code snippet:
#include <optional>
#include <iostream>
int main()
{
std::optional<unsigned> check = 200;
std::cout << check << std::endl;
...
3
votes
1
answer
105
views
Is it ok to double-dereference ("**itOpt") an optional iterator?
If I have a std::optional wrapped around (say) an
std::vector::const_iterator, is it safe to access the referenced
element with two consecutive dereference (*) operators?
For example:
typedef std::...
6
votes
1
answer
697
views
`std::optional` factory function with guaranteed copy elision and `private` constructor, without passkey idiom
Consider the following pattern:
class Widget
{
private:
explicit Widget(Dependency&&);
public:
static std::optional<Widget> make(std::filesystem::path p)
{
std::...
4
votes
3
answers
224
views
Why is it undefined behavior to call operator* on an empty std::optional if I don't access the returned value right away?
Why is it undefined behavior to call operator* on an empty std::optional if I don't access the returned value before emplacing an object?
For example, why is the following code UB?
std::optional<...
0
votes
1
answer
125
views
optional vector of enum initializer list
In the following case, when using assignment on an optional vector of enum values I cannot explain the behavior of the code. Why does assignment of ... = {C} compile and create a vector of size 2, ...
0
votes
0
answers
89
views
Does optional<reference_wrapper> not return a reference?
I wanted to make a Table class that is supposed to work like a table with columns and rows, and values in the cells. Obviously I need a function that would allow to get the value from a particular ...
0
votes
0
answers
654
views
Convert to std::optional in nlohmann::json via NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE
I need to serialize / deserialize a struct that has an optional member.
I'm using the excellent nlohmann::json library and from the docs I can see that it should be done like this:
namespace nlohmann {...
0
votes
1
answer
193
views
Is it useful to construct an std::optional using std::in_place when returning from a function?
I was just wondering, is it useful to return an std::optional from a function constructed using std::in_place? Should I be doing it blindly or does copy elision/changing C++ versions/the data ...
1
vote
1
answer
96
views
Unexpected behavior of std::is_copy_assignable and boost::optional
If I delete the copy constructor and/or the copy-assignment constructor of a type Bar,
struct Bar {
Bar() = default;
Bar(Bar const&) = delete;
};
std::optional<Bar> is not copy-...
-4
votes
1
answer
705
views
error: cannot convert 'std::optional<int>' to 'const int' in initialization
#include <vector>
#include <ranges>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
const vector<int> v = {1, 2, 3};
const int n = ...
3
votes
0
answers
335
views
Runtime Issues with std::optional in GCC on M2 Mac
I have found what I believe to be a weird bug with std::optional in GCC on my macbook. I am hoping that someone can either show me that I'm wrong, or offer guidance about where to report it.
...
0
votes
2
answers
84
views
Writing functions which handle invalid inputs in C++
In C++, how to handle function outputs , if the inputs are invalid. Say, I am writing a function to multiply two matrices. How to deal with it if the two matrices cannot be multiplied (due to in-...
4
votes
3
answers
330
views
Pass-through constructor for std::optional arguments
Alright, I messed up asking this question the first time.
Is there a way, idiomatically, to provide a constructor which takes one or more std::optional<T> and returns a std::optional<U>? ...
2
votes
1
answer
187
views
Pass-through constructor for std::optional argument
Is there a way, idiomatically, to provide a constructor/conversion which takes a std::optional<T> and returns a std::optional<U>? For instance, ideally I would love some kind of syntax ...
2
votes
2
answers
278
views
Stream insertion operator >> for std::optional
Is there a reasonably idiomatic way* to use stream insertion operators >> with std::optional? The standard class does not provide an overload for std::istream& operator>>(std::istream&...
1
vote
2
answers
103
views
Is there another way to achieve the functionality of std::optional without another object being created?
class ScopedClass {
public:
ScopedClass() {
cout << "constructor called\n";
}
~ScopedClass() {
cout << "destructor called\n";
}
ScopedClass(const ...
1
vote
2
answers
2k
views
How std::optional library handles emplace operation?
I was trying to create objects for optional variables in-place. When using emplace function in std optional library for a class, the destructor of the class is called. Does that function do copy ...
0
votes
2
answers
273
views
Getting an optional of a class derived from abstract class, from a class derived from abstract class
I have something similar to the code below, where a group of classes with similar shared behaviours (Tool1, Tool2), all inherit from an abstract class (ITool). All these classes own their own optional ...
5
votes
2
answers
729
views
Why does std::optional not use a sentinel value to represent an empty optional?
I know this ship has sailed due to ABI breakage it would require, but I wonder why originally implementations did not decide to use some magic bit pattern for std::string, std::vector, etc... to ...
1
vote
1
answer
58
views
Value corrruption with a view pointing to a value within an std::optional
I am trying to create a setting where an instance of a C++ class optionally owns the data. For this I'm creating an std::optional<Type>, and a view to this optional (or something supplied from ...
0
votes
1
answer
79
views
Copy constructor of optional using term "direct-non-list-initializes" instead of "copy constructs"
In C++ standard the copy constructor of optional is defined as follows:
constexpr optional(const optional& rhs);
Effects: If rhs contains a value, direct-non-list-initializes the contained value ...
0
votes
0
answers
91
views
std::optional<T> assignment operators
My reference is to options (4), (5) and (6) of std::optional::operator=
Given the premise that
The class template std::optional manages an optional contained value, i.e. a value that may or may not be ...
6
votes
1
answer
256
views
std::optional::transform with std::addressof
Consider the following code:
#include <memory>
#include <optional>
template <typename T>
constexpr T * arg_to_pointer(T & arg) noexcept {
return std::addressof(arg);
}
int ...
1
vote
1
answer
462
views
Pass `std::optional::value` to `std::views::transform`
I cannot seem to pass std::optional::value to std::views::transform.
However, I can pass std::optional::has_value without any issues:
#include <optional>
#include <ranges>
#include <...
1
vote
3
answers
1k
views
Interaction between std::optional<std::any> and has_value()
For debugging purposes, I was writing a function which iterates over a vector of optional variables of any type to check which ones were initialized, but the check for has_value() on all of them is ...
2
votes
1
answer
103
views
What's the point of ref-qualified member functions in `std::optional::value`
These are the signatures, according to Cppreference:
constexpr T& value() &;
constexpr const T& value() const &;
constexpr T&& value() &&;
constexpr const T&& ...
3
votes
1
answer
183
views
How would a std::optional<std::nullopt_t> operate?
Kind of a silly question, but I'm curious and I haven't found this explained. Is it legal to construct a std::optional<std::nullopt_t>? If you did, what would
std::optional<std::nullopt_t&...
1
vote
1
answer
1k
views
Forward declaration of class inside unique_ptr inside optional with default argument fails
I have the following piece of code
// DoSomething.h
class Foo;
void doSomething(std::optional<std::unique_ptr<const Foo>> f = std::nullopt);
If I include DoSomething.h anywhere without ...
5
votes
1
answer
146
views
Why doesn't iterate over a container accessed directly through std::optional<T>::value() work?
I'm trying to iterate over a std::vector<X> contained in a struct T that I access through a std::optional<T>. Contrary to my expectations, the behavior is different if I first store the ...
0
votes
2
answers
3k
views
optional refence to an object: best way?
I want a function to return an optional reference to an object. Idea is to avoid copy, but seems like i should not be using according to this discussion:
std::optional specialization for reference ...
1
vote
2
answers
421
views
std::minmax_element comparer for a vector with std::optional is incorrect
I have a struct within a struct of std::optionals, and I am trying to find the minimum and maximum value within the struct. However, using std::minmax_element seems to be inaccurate, and I've had to ...