简体   繁体   English

这是不好的做法吗? C ++

[英]Is this bad practice? C++

Class1 myclass(someparameter);

int main(int argc, char* argv[])
{
    myclass = Class1(anotherparameter);
}

I have a variable at file scope. 我在文件范围有一个变量。

I don't really know how to word my question. 我真的不知道怎么说出我的问题。 But basically I am copying a class and this code looks quite funky. 但基本上我正在复制一个类,这段代码看起来很时髦。 Are there any consequences of doing this? 这样做有什么后果吗? Should I use new / delete instead? 我应该使用new / delete吗? A potential problem I can think of is if the class contains pointers (but then that could be solved by creating a copy constructor) 我能想到的一个潜在问题是,如果类包含指针(但那可以通过创建复制构造函数来解决)

I'd say that global variables are usually undesired. 我会说全局变量通常是不受欢迎的。 It doesn't mean they are illegal or 'bad style' though. 但这并不意味着它们是非法的或“坏的风格”。 I'd definitely avoid using globals in this particular case... 在这种特殊情况下,我肯定会避免使用全局变量...

Assuming your class can correctly copy, then I don't see anything inherently wrong with this. 假设你的课程可以正确复制,那么我没有看到任何内在错误。 But it's not all that efficient since myclass is actually initialized twice: once where it's declared, and again where you assign another instance to it. 但是,由于myclass实际上被初始化了两次,所以效率并不是那么高效:一次声明它,再次指定另一个实例。

If that's what your logic requires, it's okay. 如果这是你的逻辑需要的,那没关系。 Otherwise, you could make your code more efficient. 否则,您可以提高代码的效率。

There's nothing wrong with what you've done, though it's not clear what the point is. 你所做的事情没有错,虽然目前尚不清楚这一点是什么。 Sometimes this kind of thing is done conditionally - for example, if command line arguments specify an alternative value for the variable. 有时这种事情是有条件的 - 例如,如果命令行参数指定变量的替代值。 You do not need to use new and delete... in this case you're asking the compiler to create a temporary object that will then be copied into the global variable (using its operator= ), then the temporary will be destroyed. 您不需要使用new和delete ...在这种情况下,您要求编译器创建一个临时对象,然后将其复制到全局变量中(使用其operator= ),然后临时对象将被销毁。 The efficiency is typically at least a little worse than when directly constructing a variable with the desired value directly, but no point in premature or unnecessary optimisation. 效率通常至少比直接构造具有期望值的变量更差,但在过早或不必要的优化中没有意义。

For comparison, consider: 为了比较,请考虑:

std::string sep = "\n";

int main(...)
{
    if (...)
        sep = std::string("\r\n");
}

This is doing more or less the same thing, though here the explicit construction of a std::string temporary is optional as that class happens to have an operator=(const char*) . 这或多或少都是一样的,尽管这里std::string临时的显式构造是可选的,因为该类碰巧有一个operator=(const char*) All good. 都好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM