Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an empty set with "return std::set<int>()" - why does it run?

Don't understand why return std::set<int>(); gives back an empty std::set<int>. Is there an operator-overload for the operator () in the std::set class ? I assumed the std::set<int>() is a function and not an object ! Where is this function defined ?

It seems that the the default constructor std::set<int> s; is the same like the expression std::set<int>() ???

Thanks for any reply ... seems i don't understand the C++ basics...

like image 386
zorro47608 Avatar asked Jan 10 '23 19:01

zorro47608


1 Answers

std::set<int>(), when used as an expression, is a temporary, default-constructed instance of std::set<int>.

First of all, std::set<int> is a type. As such, C++11 §5.2.3 [expr.type.conv]/2 explains what happens:

The expression T(), where T is a simple-type-specifier or typename-specifier for a non-array complete object type or the (possibly cv-qualified) void type, creates a prvalue of the specified type, whose value is that produced by value-initializing (8.5) an object of type T; no initialization is done for the void() case.

Value-initialization has many rules, but for a class like std::set<int>, it is equivalent to default-initialization, which just calls the default constructor. Since the default constructor of std::set<int> produces an empty set, that's what you get.


Worth noting is that had you put arguments in the parentheses, these arguments would be passed to the appropriate constructor. In that regard, this is like any other constructor call for creating a temporary object.

Also worth noting is that std::set<int>() does not always do what I described. Notice that I said when used as an expression. If this appears where a type could appear, it is a valid type as well. In particular, it is a function with no parameters that returns a std::set<int>. Since return is followed by an expression, this must be treated as an expression rather than a type.

like image 100
chris Avatar answered Jan 25 '23 11:01

chris