简体   繁体   中英

Usage of Uniform Initialization Syntax

If I have a class

class Foo
{
public:
    Foo();
    Foo(int bar);

private:
    int m_bar;
}

What is the difference between these two ways to initialize it's member

Foo::Foo(int bar):
    m_bar(bar)
{

}

Foo::Foo(int bar):
    m_bar{ bar }
{

}

I was told on a code review to use Uniform Initialization Syntax, ie brace initialization. Is there a difference in this case? Or is it just a style preference?

In case of simple types, like int in your case, there is no difference. However, initialization of std::vector from STL will be completely different

std::vector<int> v1(3,1); // v1 consists of: 1, 1, 1
std::vector<int> v2{3,1}; // v2 consists of: 3, 1

Have a look at this answer if you want to see why generally brace {} initialization is better, however quoting from Scott Meyer's book Effective Modern C++ , which I highly recommend:

[...] So why isn't this Item entitled something like “Prefer braced initialization syntax”? The drawback to braced initialization is the sometimes-surprising behavior that accompanies it. [...]

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