C++班级成员分配

发布于 2024-12-11 03:18:20 字数 405 浏览 0 评论 0原文

假设我有这个:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

流年里的时光 2024-12-18 03:18:20

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.

北座城市 2024-12-18 03:18:20

假设 Member 不是指针类型的 typedef,即它的 not 定义为,比如说,

typedef int* Member;

您不必执行任何操作来分配它,因为它是在以下情况下自动分配的:您分配 foo 的实例。

Assuming Member is not a typedef for a pointer type, i.e. it's not defined as, say,

typedef int* Member;

you don't have to do anything to allocate it as it is automatically allocated when you allocate instances of foo.

你在看孤独的风景 2024-12-18 03:18:20

编辑:我应该如何告诉他使用哪个构造函数?(很抱歉不清楚)

如下所示:

foo::foo() : member(...) // member initializer list
{
}

EDIT: How should I tell him which constructor to use?(sorry for being unclear)

like this:

foo::foo() : member(...) // member initializer list
{
}
云淡月浅 2024-12-18 03:18:20

我应该如何告诉他使用哪个构造函数?

类声明中的 Member member 尚未调用任何构造函数,因为它只是声明。但是,当您稍后定义它时,应该使用 member()membermember(arg,..) 来定义成员对象并调用某个构造函数。

代码很好并且可以工作。请注意,它将调用赋值运算符而不是复制构造函数。

How should I tell him which constructor to use?

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 use member(), member or member(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文