I have questions about std::stack
Why these two constructors are explicit
?
explicit stack( const Container& cont = Container() );
explicit stack( Container&& cont = Container() );
Note: Source
I have questions about std::stack
Why these two constructors are explicit
?
explicit stack( const Container& cont = Container() );
explicit stack( Container&& cont = Container() );
Note: Source
The constructors are explicit so you can't accidentally pass an underlying container (such as vector
or deque
) to a function expecting a stack
, resulting in unexpected copying (not to mention violating the principle of least surprise).
One problem is that if you assume implicit invocation, what would happen if others followed your example? So for instance the following fails to compile
#include <iostream>
#include <vector>
using namespace std;
class Test {
public:
Test(const std::vector<int>&) {
cout << "Test(const std::Vector<int>&)" << endl;
}
};
class AnotherTest {
public:
AnotherTest(const std::vector<int>&) {
cout << "AnotherTest(const std::Vector<int>&)" << endl;
}
};
void test_function(const AnotherTest&) {
cout << "fucntion(const AnotherTest&)" << endl;
}
void test_function(const Test&) {
cout << "fucntion(const Test&)" << endl;
}
int main() {
const std::vector<int> vec {1, 2, 3};
test_function(vec);
return 0;
}
You can easily see this problem occurring with a stack
and a queue
.