Archie Gertsman
Archie Gertsman

Reputation: 1661

C++ Function that is Only Called Once

I'm working on a project and to clean the code up in a big function, there is a segment of it that I think should be a separate function. But that separate function will only be used once, inside that bigger function. How should I treat it? Should it just be a normal void or is there a keyword I can throw before it? Could it be an inline function? I've heard of those but don't totally understand what they do. Thanks!

Upvotes: 1

Views: 817

Answers (4)

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21748

It is normally recommended to place a code with the single, clearly defined responsibility into dedicated function, even it that function is only called once. At least this is that I have seen in all books on topic.

This make the code more readable, maintainable and also you can now write a Unit test for the extracted function. If the function is unlikely to require dedicated testing (well covered with wider Unit tests, etc), you can still define it separately in the same file with static keyword, so it does not conflict with anything outside.

Upvotes: 0

daparic
daparic

Reputation: 4454

Granting the run once need is inside a namespace, I thus instantiate a RunOnce object and passing a lambda:

namespace mystuff {
    int somevars = 5;
    RunOnce initialize([&](){
       // do one-time initalization here
       somevars = 0;
    });
}

Where,

class RunOnce {
public:
    RunOnce(std::function<void(void)> init) {
        init();
    }
}

Upvotes: 0

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

Stick it in the same source (.cpp) file. Place it within a namespace {} -- an anonymous namespace. This guarantees it cannot be used/referred to outside of that source file, which both communucates to developers and compilers somewhat useful information.

inline all by itself is a bad idea due to potential odr violations (if another independent function with the same signature and name exists, bad things would happen). For "famous" functions in header files the risk is mitigated somewhat. inline once you put it in an anonymous namespace is innocuous, and may give amcompiler a hint that may be useful. It probably does not matter.

Upvotes: 2

Bart
Bart

Reputation: 547

inline is used for small and simple functions where you want to avoid the overhead of calling the function. It basically copies the code of the inline function inside your bigger function.

http://www.cplusplus.com/articles/2LywvCM9/

Upvotes: 1

Related Questions