C ++的新手 - 到目前为止的正确方法? [英] New to C++ - right approach so far?

查看:92
本文介绍了C ++的新手 - 到目前为止的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





作为虚幻引擎4的个人项目的一部分,我正在学习c ++。经过深思熟虑后,我想我终于开始理解一些你用管理语言看不到的新概念了。我的目标如下:



1.正确管理所有内存以避免任何内存泄漏

2.将所有代码作为尽可能紧凑而不丑陋

3.尽可能遵守c ++标准



如果你能指出任何改变你我写这个代码,请告诉我。一旦我知道我应该如何正确地编写代码,我就可以自信地将它应用到我编写的项目的其余部分。



这个类叫做ContainerAttributes,并且实际上是名称和值的字典,例如容量是100,健康是75等。因为不同的对象将具有不同的存储信息,例如。一些项目可能是无敌的,可能没有健康属性,我不是硬编码任何东西,而是我允许程序员动态指定属性和值。



.h:

Hi,

As part of a personal project with Unreal Engine 4, I'm learning c++. After much deliberation I think I'm finally starting to understand some new concepts which you simply don't see with managed languages. My goals here are as follows;

1. To manage all memory properly to avoid any memory leaks
2. To have all code as compact as possible while not being ugly
3. To abide by c++ standards as much as possible

If you could point out any changes you'd make to this code I've written, please let me know. Once I know how I should be writing the code properly, I can confidently apply that to the rest of my project as I write it.

This class is called ContainerAttributes, and is effectively a dictionary of names and values, for example capacity is 100, health is 75 etc. As different objects will have different storage information, eg. some items may be invincible and may have no health attributes, I'm not hardcoding anything in, rather I'm allowing the programmer to specify the attributes and values dynamically.

.h:

#pragma once

#include "DebugHelper.h"

#include "CoreMinimal.h"

class NOCTURNALSYNERGY_API ContainerAttributes
{
public:
    ContainerAttributes();
    ~ContainerAttributes();
	void SetValue(string name, int value);
    int GetValue(string name);

    void Debug();

private:
    map<string, int> values;

};





正如我所提到的,我没有内存管理方面的经验,但我知道任何创建的东西'new'返回指向对象的指针,必须使用'delete'删除该指针以释放内存。据我所知,〜方法是解构器,在以下情况下会出现;





As I mentioned, I have no experience with memory management but I understand that anything created with 'new' returns a pointer to the object which must be deleted to free memory using 'delete'. To the best of my knowledge as well, ~ methods are deconstructors, which would come about in the following situation;

obj->containerAttributes = new ContainerAttributes();
obj->whatever();
delete obj;

(then inside obj)
obj::~obj()
{
delete containerAttributes;
}





这应该调用ContainerAttributes中的解构函数,它可以释放它的内存(值映射)。



.cpp:



This should consequently call the deconstructor in ContainerAttributes which can free its memory (the values map).

.cpp:

#include "ContainerAttributes.h"

ContainerAttributes::ContainerAttributes()
{
    values = new map<string, int> {};
}

ContainerAttributes::~ContainerAttributes()
{
    delete values;
}

void ContainerAttributes::SetValue(string name, int value)
{
    auto it = values.find(name);

    if(it != values.end())
    {
        values[name] = value;
    }
    else
    {
        values.insert(pair<string, int>(name, value));
    }
}

int ContainerAttributes::GetValue(string name)
{
    auto it = values.find(name);

    if(it != values.end())
    {
        return it->second;
    }
    else
    {
        DebugHelper::Debug("Error in ContainerAttributes; map does not contain name '" + name + "'");
    }
}

void ContainerAttributes::Debug()
{
    map<string, int>::iterator it;

    for(it = values.begin(); it != values.end(); it++)
    {
        DebugHelper::Debug(it->first + ": " + it->second);
    }
}





关于此的一些其他问题,DebugHelper :: Debug接受FString。甚至可以使用'+'以这种方式连接字符串,还是必须使用其他方法?我很高兴创建一个额外的方法来接受std :: string,但我不确定'+'是否也能在那里工作。



最后,最好使用



A few other questions regarding this, DebugHelper::Debug accepts an FString. Is it even possible to concatenate strings in this way using '+' or do I have to use another method? I'm happy to create an additional method to accept std::string as well, but I'm not sure whether '+' will work there either.

Finally, is it best to use

auto it = values.find(name);



或者我应该明确指定这样的东西吗?


or should I explicitly specify something like this?

pair<string, int> it = values.find(name);





感谢您提供任何帮助。



我尝试过:



---------------- -------------------------------------------------- --------



Thanks for any help you can give.

What I have tried:

--------------------------------------------------------------------------

推荐答案

如果避免使用已分配的成员变量,则会自动调用成员的析构函数,以减少内存泄漏的可能性。使用 obj 示例,您可以通过将成员从 * ContainerAttributes 更改为 ContainerAttributes 。



你也可以考虑让你的 ContainerAttributes class std :: map 基于:

If you avoid using allocated member variables, the destructor of members is called automatically reducing the chance of having memory leaks. With your obj example it looks like you can do that by changing the member from *ContainerAttributes to ContainerAttributes.

You might also think about making your ContainerAttributes class std::map based:
class NOCTURNALSYNERGY_API ContainerAttributes : public std::map<std::string, int>
{
public:
    ContainerAttributes();
    ~ContainerAttributes();
    void SetValue(const std::string& name, int value)
    {
        auto it = find(name);
        if (it != end())
            it->second = value;
        else
            insert(std::pair<std::string, int>(name, value));
    }
    int GetValue(const std::string& name) const
    {
        const auto it = find(name);
        return it == end() ? -1 : it->second;
    }
};

但是,这样可以公开访问地图。另请注意,我已将 name 参数更改为 const 并通过引用传递,这是适当的传递。



根据 FString |虚幻引擎 [ ^ ]文档它提供了一个 + = 运算符(可能只是在内部调用 Append()) 。因此,您可以使用 + 运算符。但在你的情况下

However, this will make access to the map public. Note also that I have changed the name parameters to be const and passed by reference which is the appropriate passing here.

According to the FString | Unreal Engine[^] documentation it provides a += operator (which probably is just calling Append() internally). So you can use the + operator. But in your case

DebugHelper::Debug(it->first + ": " + it->second);

操作是在(和as) std :: string 上执行,而不是在 FString 上执行。





何时使用 auto ,何时不是您的决定,通常根据具体情况选择。只需在网上搜索c ++ auto or not等内容。一个可能很好的阅读:不要使用< auto>除非你的意思 - 约瑟夫曼斯菲尔德 [ ^ ]。

the operation is performed on (and as) std::string and not on FString.


When to use auto and when not is your decision and commonly choosen depending on the context. Just search the web for something like "c++ auto or not". A probably good read: Don't use <auto> unless you mean it — Joseph Mansfield[^].


这篇关于C ++的新手 - 到目前为止的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆