0

I have got an Element, which is a std::vector in a std::optional. Now I want to emplace an Element to the vector (via emplace_back):

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <optional>

int main()
{
    std::optional<std::vector<uint8_t>> optvec;
    optvec->reserve(1);

    optvec->emplace_back(1);

    std::cout << optvec.has_value() << std::endl;

    return 0;
}

However, regarding the memory, this emplaces the element itself correctly, but the optional part doesn't get it that there is an element, so it's a nullopt.

Is there another way to do this? Thanks in advance.

Gabriel
  • 11
  • 5

3 Answers3

4

When you do

std::optional<std::vector<uint8_t>> optvec;
optvec->reserve(1);

your program has undefined behaviour, in much the same way as if you had done

std::vector<uint8_t> * optvec{ nullptr };
optvec->reserve(1);

Why do you want an optional vector in the first place? A vector can already hold zero elements.

Is there another way to do this?

Have a (potentially empty) plain vector.

std::vector<uint8_t> optvec;
Caleth
  • 52,200
  • 2
  • 44
  • 75
  • i need this because i've got a much bigger structure holding different types, and all Elements which aren't always present are defined as optional, so the vectors too. But thanks, good hint, maybe it's avoidable. – Gabriel Jul 14 '21 at 10:01
3

Your optional does not contain any vector. The default constructor of optional builds it an object that does not contain any value.

You can simply

std::optional<std::vector<uint8_t>> optvec = std::vector<uint8_t>();

or...

std::optional<std::vector<uint8_t>> optvec;
optvec.emplace();

and then you have an actual vector in your optional

Federico
  • 743
  • 9
  • 22
0

Is there another way to do this?

Yes, give the optional a value

int main()
{
  std::optional<std::vector<uint8_t>> optvec;
  assert(!optvec.has_value());

  optvec = { 'a', 'b', 'c' };
  assert(optvec.has_value());

  optvec.value().emplace_back('d');
}
Andreas DM
  • 10,685
  • 6
  • 35
  • 62