【问题标题】:Why are these constructors of std::stack explicit为什么 std::stack 的这些构造函数是显式的
【发布时间】:2016-11-01 08:02:27
【问题描述】:

我对@9​​87654325@有疑问,为什么这两个构造函数是explicit

     explicit stack( const Container& cont = Container() );
     explicit stack( Container&& cont = Container() );

注意: Source

【问题讨论】:

标签: c++ c++11 stack


【解决方案1】:

构造函数是显式的,因此您不会意外地将底层容器(例如 vectordeque)传递给期望 stack 的函数,从而导致意外复制(更不用说违反了最小原则)惊喜)。

【讨论】:

    【解决方案2】:

    一个问题是,如果你假设隐式调用,如果其他人效仿你的例子会发生什么?因此,例如以下无法编译

    #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;
    }
    

    stackqueue 可以很容易地看到这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-09
      • 2016-12-15
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 2014-07-16
      相关资源
      最近更新 更多