union error

Hi

When I uncomment the union anonymous struct the code won't compile.
Any ideas anyone?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

int main() {

  struct stock_item {
    std::string category;
    float      q{0.0}; 
    float      unit{0.0}; 
    double     price{0};
//    union { 
//      unsigned long long   stock_id{0};
//      std::string stock_name;
//    };
  };

  stock_item products[100]{};
  
  return 0;

}
std::string is a complex type, I don't think you can make a union with it.
Hi,

It looks like one cannot have a std::string as a member of a union. The code compiles without the string on line 13.

cppreference wrote:
A union cannot have data members of reference types.


cppreference wrote:
The union is only as big as necessary to hold its largest data member. The other data members are allocated in the same bytes as part of that largest member.



The size of the string cannot be known, so that's why the compiler complains.

http://en.cppreference.com/w/cpp/language/union
std::string has constructor and destructor so it is generally not safe storing it in a union. C++ will allow it if you add constructor and destructor for the union but then you need to explicitly create the string object using placement new and destroy it by calling the destructor explicitly. You might also want to make the data members of the union private to prevent the string from being accidentally assigned to (or otherwise accessed) while it's not constructed. I don't think anonymous unions can have constructors and destructors so you would probably have to use a named union instead.

If you know approximately how long the strings are going to be it might be easier to use a fixed size char array (C-string) instead of std::string.

But honestly, do you really need to use a union here? Why not make stock_id and stock_name members of stock_item?
Last edited on

thanks, compiled when modified to:
1
2
3
4
union {
      unsigned long long   stock_id{0};
      char stock_name[20];
    };


at times, a stock item may not be allocated an ID, so a temporary name applies, but when an ID is allocated, then the string no longer applies, hence the union.
How do you know if you should use stock_id or stock_name? Does the category tell you that?
yes, category combined with a new attribute inWarehouse bool, which I didn't include in my first post. The struct in fact has many more attributes than what I originally posted.
Topic archived. No new replies allowed.