1

It's amazing that std::set be converted to MySet, but how to avoid ?


#include <bits/stdc++.h>

struct MySet : public std::set<int> {
  MySet(const std::set<int>& s) {
  }
};

std::set<int> get(int i) {
  return std::set<int>{i};
}

int main() {
  const MySet& a = get(0);
  std::cout << a.empty() << std::endl;  // true
}

const MySet& a = get(0); should give compile error.

Jason
  • 36,170
  • 5
  • 26
  • 60
whiker
  • 13
  • 5
  • 2
    Why add the constructor if you don't want this behavior? – HolyBlackCat Dec 29 '22 at 11:26
  • 1
    You have a converting constructor that converts a `std::set` to a `MySet`. – Jason Dec 29 '22 at 11:26
  • 4
    Please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and then *never* include that header ever again. – Jesper Juhl Dec 29 '22 at 11:26
  • 3
    Make the constructor `explicit`. – Jason Dec 29 '22 at 11:27
  • The constructor `MySet(const std::set& s)` is a so-called *converting* constructor. It allows implicit conversion from `std::set` to `MySet`. – Some programmer dude Dec 29 '22 at 11:27
  • So the reference isn't bound to a `std::set`, but to a `MySet` constructed from `get(0)`. A const reference can be bound to a temporary, so that's what happens here. – BoP Dec 29 '22 at 12:03
  • I'm also very curious about why you need `MySet`. And why you need to mix `std::set` and `MySet` like you do with `const MySet& a = get(0)` What is the actual and underlying problem that `MySet` and `get` are supposed to solve? – Some programmer dude Dec 29 '22 at 12:25

1 Answers1

3

const MySet& a = get(0); should compile error

This can be done either by removing the converting ctor MySet::MySet(const std::set<int>&)or by making it explicit as shown below:

struct MySet : public std::set<int> {
//vvvvvvvv---------------------------------->make this ctor explicit
  explicit MySet(const std::set<int>& s) {
  }
};

int main() {
  const MySet& a = get(0);
  std::cout << a.empty() << std::endl;  // gives error now
}
Jason
  • 36,170
  • 5
  • 26
  • 60