简体   繁体   中英

which return comply with C++ standard

class A {};

class B 
{
public:
    B(const A& a, int i = 10) : m_a(a), m_i(i) {}
private:
    int m_i;
    A m_a;
};

B getB(void)
{
    //return B(A());  // Method one
    //return A();     // Method two
}

Both method one and method two pass the compilation of VS2010.

Question 1 > Which one is better?

Question 2 > Is it true that an implicit constructor supports more than one pass-in parameters if all except the first parameters have default values?

Thank you

Both are valid and both do the same thing. I'd use the first one because I find the second one confusing, but different strokes for different folks.

EDIT: Actually, I'd do even more than that. I'd mark B 's constructor as explicit in order to prevent just the sort of thing that makes the second one compile.

Note: I would avoid use of (void) in method signatures in C++.

Both are correct. First one explicitly creates B instance, and the second one implicitly creates B from A . I like neither of those. They just increase confusion level and nothing more.

I would decorate the constructor as explicit , and then use method one as the only available method:

class B {
public:
    explicit B(A const & a, int b = 10) : m_a(a), m_i(b) { }
    // ...
};

B foo()  { return B(A()); }

That way you can never accidentally construct a B from an A . If the constructor of B is expensive or may throw, then having this extra level of deliberateness in your code may well help make it more readable and less error-prone.

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