简体   繁体   中英

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? 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.

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. 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*) . All good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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