我目前正在优化我的代码,并且在初始化我的类时我很想使用以下模式:
class MyClass
{
MyClass(int x) :
_x(x),
_collection(createCollection())
{
}
int functionThatDependsOnTheStateOfTheClass() const
{
return _x;
}
private:
std::vector<int> createCollection() const
{
std::vector<int> collection;
// The collection is dependent on _x somehow.
collection.push_back(functionThatDependsOnTheStateOfTheClass());
return collection:
}
const int _x;
const std::vector<int> _collection;
};
我完全明白,使代码隐式依赖于这样的初始化顺序是危险的,但代码是否以其他方式出错?
请注意,上面的代码非常简单。我想这样做的原因是:
所以我的问题是:我应该像瘟疫一样避免这种模式,还是在某些情况下可以接受?
答案 0 :(得分:4)
现在你的代码定义得很好。 The order of initialization of nonstatic data members of a class is:
然后,非静态数据成员应按其顺序初始化 在类定义中声明(再次无论顺序如何) 记忆初始化者。)
由于在def show(request, pk):
try:
project = Project.objects.filter(
pk=pk,
source_language=source_language,
target_languages__in=[target_language]
).first()
except Exception as e:
raise Http404()
if not project:
#instead of this do what? print message no project, return to previous page
raise Http404()
#return HttpResponseRedirect(request.META.get('HTTP_REFERER')) still generates error from non URL match
之前宣布_x
,_collection
将被初始化,因此可以在_x
中使用。