实例化一个新的STL向量
我遇到的情况是,我有一个指向 STL 向量的指针。
就像
vector<MyType*>* myvector;
我必须在构造函数中将此指针设置为 NULL,然后在触摸属性时延迟加载一样。
如何将其实例化为向量的新实例?
I have a situation where I have a pointer to an STL vector.
So like
vector<MyType*>* myvector;
I have to set this pointer to NULL in the constructor and then lazy load when the property is touched.
How can I instantiate this to a new instance of a vector?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设您正确定义向量:
初始化为 NULL
首次使用时实例化:
但是您不应该将原始指针作为类的成员(除非有很好的理由)。 您将需要编写自己的复制构造函数和赋值运算符。
或者,您也可以用智能指针包装“myvector”。 或者更好地使其成为法线向量。 没有真正需要将其设为指针。
Assuming you define vector correctly:
Initialize to NULL
Instantiate on first use:
But you should not have a raw pointer as a member to your class (unless there is a very good reason). You will need to write your own copy constructor and assignment operator.
Or alternatively you can wrap 'myvector' with a smart pointer. Or even better make it a normal vector. There is no real need to make it a pointer.
我不确定我是否完全理解你。 为什么不简单地将向量留空,并设置一个布尔值来表示该属性是否已加载? 或者,您可以使用
boost: :可选
:或者
您可以通过取消引用可选对象来简单地接收该对象,并像往常一样为其分配一个向量。
我不会为此使用指针。 这使事情变得复杂,你必须考虑当你复制包含属性的对象时会发生什么,...
如果你确实必须使用指针,你可以这样做:
或者使用
shared_ptr
,这将是我的程序中的方法(但是 boost::Optional 仍然是第一个选项,之后是向量和布尔选项,之后是以下选项)复制和分配被禁用,因为它们将共享幕后的属性(浅复制),这应该清楚地记录或通过这些函数中的深层复制来禁用。
I'm not sure I understand you all the way. Why not simply leave the vector empty, and set a Boolean that says whether the property was loaded or not? Alternatively, you can use
boost::optional
:Or
You can then simply receive the object by dereferencing the optional object, and assign a vector to it like usual.
I would not use a pointer for this. It complicates the matter, and you have to think about what happens when you copy the object containing the property, ...
If you really have to use a pointer, you can do it like this:
Or use
shared_ptr
, which would be the way to go in my program (but boost::optional would still be first option, after which would be the vector-and-Boolean option, after which would be the following)Copy and assignment are disabled, as they would share the property behind the scene (shallow copy), which should be either clearly documented or disabled by deep copying in these functions.
你不能有这样的指针:
因为向量是一个模板类并且必须有一个类型。 你可以说:
或者:
然后动态创建一个向量:
You cannot have a pointer like this:
Because vector is a template class and must have a type. You could say:
Or:
And then dynamically create a vector:
好吧,要初始化它,您至少需要使用该语法将其设置为 NULL 或如下所示的实例。 另外,您应该按照声明字段的顺序执行此操作,否则可能会发生奇怪的事情。
Well, to initialize it, you will need to at least set it to NULL or an instance like below using that syntax. Also you should do it in the order the fields are declared, otherwise weird stuff might happen.