Sah*_*wal -1 c++ constructor factory-method segmentation-fault
我有以下功能
LinearScheme::LinearScheme() {
cout << " empty constructor" << endl;
}
void LinearScheme::init(
int tableId,
std::string &basePath,
std::vector<size_t> &colElemSizes,
TupleDescMap &tupleDescMap,
size_t defaultMaxFragmentSize,
int numCols,
BoundBases &bounds,
std::vector<int> &colsPartitioned )
{
// This linear scheme ignores bounds
// it could be improved to use colsPartitioned for ordering (TODO)
cout << "init Linear Scheme " << endl;
*this = LinearScheme(); //SEGFAULTS HERE
cout << "after cons here?" << endl;
// init private fields
this->tableId_ = tableId;
this->basePath_ = basePath;
this->colElemSizes_ = colElemSizes;
this->numCols_ = numCols;
this->tupleDescMap_ = tupleDescMap;
this->numFragments_ = 0;
this->defaultMaxFragmentSize_ = defaultMaxFragmentSize;
// fragmentSizesFilename_ init
fragmentSizesFilename_ = basePath_ + boost::lexical_cast <string>(tableId_)
+ "_cs";
struct stat st;
// open existing file if exists. Create new otherwise.
if (stat(fragmentSizesFilename_.c_str(), &st) == 0) // file existed
openExisting();
else
createNew();
}
Run Code Online (Sandbox Code Playgroud)
我初始化init而不是构造函数的原因是因为LinearScheme扩展了一个PartitionScheme(带有虚方法的超类)类而另一个类做了递归使用构造函数的那个.
我有一个QuadTree类进行相同的初始化,因为每个QuadTree构造函数都是递归应用的.*this = QuadTree(bounds, maxSize) 在QuadTree类的init函数中的行工作得很好.
但是,另一个子类(LinearScheme)中的这一行*this = LinearScheme()会导致Seg错误.
任何想法为什么会这样?
编辑 也替换线:
*this = LinearScheme()
Run Code Online (Sandbox Code Playgroud)
有了这个:
*this;
Run Code Online (Sandbox Code Playgroud)
或整体删除它摆脱了Seg Fault ......为什么?
听起来不正确factory method/ builder/ deferred construction使用.对于许多这些对象创建模式函数,构造对象应该是一个静态方法,因为还没有一个要操作的实例.在其他人中,您可能会操纵已构造的实例.在任何一种情况下,如果你实际上在函数中构造类类型的对象,你应该使用new并最终返回它.
如果您正在寻找一种helper方法来协助初始化,那么您根本就不应该在方法本身内构建对象,而应该只是在帮助器中初始化它的一部分.
工厂模式示例:
LinearScheme* LinearScheme::create(...all_your_args....) {
/* construct the thing we are building only if it
* pass any arguments into him that he can handle directly if you'd like
*/
LinearScheme *out = new LinearScheme(...);
/* do whatever else you have to do */
....
return out;
}
Run Code Online (Sandbox Code Playgroud)
或者helper你似乎想要的那种
/* this time let's just do 'init' on your object */
void LinearScheme::init(....args....) {
/* possibly check if init has been done already */
if ( this->init ) return;
/* proceed to do your initialization stuff
* but don't construct the 'this' instance since it should already exist
*/
this->init = true; //so we don't init again if you don't need multiple init's
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以考虑C++ 11 alex提及中的委托构造函数方法.
然而,这些都不是真正让我感到困扰的是这里的实际问题.
它不起作用,因为你可能甚至没有一个有效*this的尊重.这可能是因为您的使用,或者可能是因为无法递归而无法创建.
这是关于模式的维基百科链接:http://en.wikipedia.org/wiki/Factory_method_pattern
鉴于你所说的不得不继续将十几个参数传递给父类和你的递归构造,你可以考虑的一个建议是创建一个小的配置结构,你通过引用传递而不是所有的离散参数.这样,每次添加/删除其他参数时,您都不必一直调整每个签名.
另一个想法是完全分离你的一个对象的构造,而不是知道如何,何地,何时应该构建它们并将其插入到层次结构中.很难说没有理解你将如何使用LinearSchme以及界面是什么.
| 归档时间: |
|
| 查看次数: |
381 次 |
| 最近记录: |