0

I have a pretty heavy object in my code which is static. I was wondering if you move the initialization of the member variables outside of the constructor, would they execute every time or just once?

struct test
{
    int a;
    int b;
};
void foo() {

    static test T;
    T.a=123;
    T.b=341;

}

int main()
{
    foo();
    foo();
    foo();
}

Will

T.a=123;
T.b=341;

be executed every time foo() is called?

0

1 Answer 1

1

that's not initialization, that's assignments, and yes, it will. Only creation of object (including initialization) happens once.

static test T = {123,341}; //happens only once.

or any other appropriate initialization, as long as all assignments or initializations are done in constructor body.

Sign up to request clarification or add additional context in comments.

7 Comments

Unfortunately for my project this throws could not convert ... from <brace-enclosed initializer list>. This stems from the fact that I do not have c++17 support( c++17 is not an option for this project).
@A.Hristov pardon me, that's C++98 for this particular case, C++11 in general case. You have some different declaration of actual structure, e.g. a constructor present. DO appropriate initialization ,
I don't think the error has anything to do with missing c++17-support, but stems form the fact that you haven't declared a constructor for test (one like this: test(int _a, int _b) : a(_a), b(_b) {}
@melk likely he got any other constructor present. this syntax ( assignment-style initialization with braced initializer) works with trivial structures since 98. In C++11 it is re-classified into initialize list. It won't work in any standard if he got a ctor.
@swift Wouldn't not declaring a constructor result in the default-constructor being created, which doesn't take any arguments, and thus wouldn't work with an initializer-list?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.