C++班级成员分配
假设我有这个:
class foo{
Member member;
foo();
~foo();
};
我应该如何分配成员?
编辑:我应该如何告诉他使用哪个构造函数?(很抱歉不清楚)
现在我已经知道 member = Member(...);
语法
这会导致内存泄漏吗?
{
Memory *temp = new Member();
member = *(temp); //will it work at all??(is it copy constructor?)
delete temp;
}
Assume I have this:
class foo{
Member member;
foo();
~foo();
};
How I should allocate the member?
EDIT: How should I tell him which constructor to use?(sorry for being unclear)
Now I already know about the member = Member(...);
syntax
Will this cause memory leak?
{
Memory *temp = new Member();
member = *(temp); //will it work at all??(is it copy constructor?)
delete temp;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C++ 不是 Java。该成员已被分配。它是它所在实例内存的一部分。它将由包含实例的构造函数构造(初始化)。关键字 new 与非指针成员无关。
C++ is not Java. This member is already allocated. It is part of the memory of the instance it is in. It will get constructed (initialized) by the constructor of the containing instance. The key word new has nothing to do with a member that is not a pointer.
假设
Member
不是指针类型的 typedef,即它的 not 定义为,比如说,您不必执行任何操作来分配它,因为它是在以下情况下自动分配的:您分配 foo 的实例。
Assuming
Member
is not a typedef for a pointer type, i.e. it's not defined as, say,you don't have to do anything to allocate it as it is automatically allocated when you allocate instances of
foo
.如下所示:
like this:
类声明中的
Member member
尚未调用任何构造函数,因为它只是声明。但是,当您稍后定义它时,应该使用member()
、member
或member(arg,..)
来定义成员对象并调用某个构造函数。代码很好并且可以工作。请注意,它将调用赋值运算符而不是复制构造函数。
Member member
in class declaration is not calling any constructor yet as it is just declaration. However, when you define it later on you should usemember()
,member
ormember(arg,..)
to define the member object and calling a certain constructor.The code is fine and it works. Just note that it will call the assignment operator and not the copy constructor.