Search code examples
c++gccgcc-warning

GCC check the reference type is same with value


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.


Solution

  • 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
    }