简体   繁体   English

使用初始化列表时检查传递给构造函数的参数-C ++

[英]Check parameters passed to constructor when using initialization lists - C++

I have a class containing vectors as data members. 我有一个包含向量作为数据成员的类。

When calling the constructor, I wish for said data members to be initialized by the copy constructor and not default initialized (to empty vector object), therefore I use an initialization list. 调用构造函数时,我希望上述数据成员由副本构造函数初始化,而不是默认初始化(针对空向量对象),因此,我使用初始化列表。

#include <vector>
using namespace std;

struct MyStruct {
    vector<double> V;
    vector<double> A;
    vector<double> B;

    MyStruct (vector<double> vee, vector< vector <double> > mat);
};

MyStruct::MyStruct (vector<double> vee, vector< vector <double> > mat)
    : V(vee),
    A(mat[0]),
    B(mat[1])    
{
    /* Rest of the constructor here*/ 
}

My questions are: 我的问题是:

  • Does doing this improves efficiency vs. permitting the default initialization and the using other methods? 与允许默认初始化和使用其他方法相比,这样做是否提高了效率? eg doing 例如做

    V.assign(vee)

  • Is there a way to have checks and errors/messages be returned by the constructor before either default-initialization or list-initialization takes place? 有没有办法让构造函数在默认初始化或列表初始化发生之前返回检查和错误/消息?

I would like for the ctor to eg halt if the size of the vector<vector<double>> > 2, for the obvious reason that otherwise the above would produce a seg fault and I would like this process to be automated when the constructor is called. 我想让ctor例如停止vector<vector<double>> 2的大小,这是显而易见的原因,否则上面的操作会产生seg错误,并且我希望在构造函数为调用。

I suppose if you want to avoid an exception you could do something like this. 我想如果您想避免例外,可以执行以下操作。 It uses the ternary operator to check the size of the vector and use an empty vector to initialize if one is not present in mat . 它使用三元运算符检查vector的大小,如果mat不存在一个vector ,则使用空vector进行初始化。

#include <vector>
using namespace std;

struct MyStruct {
    vector<double> V;
    vector<double> A;
    vector<double> B;

    MyStruct (vector<double> vee, vector< vector <double> > mat);
};

MyStruct::MyStruct (vector<double> vee, vector< vector <double> > mat)
    : V(vee),
    A(mat.size() < 1 ? vector<double>():mat[0]),
    B(mat.size() < 2 ? vector<double>():mat[1])
{
    // If you then want to throw your own exception:
    if(mat.size() < 2)
        throw std::range_error("accessing mat");

    // alternatively set a flag
    if(mat.size() < 2)
        this->good = false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM