简体   繁体   中英

How do implicitly declared (object level) member functions work according to the ISO C++11 standard?

Are these class definitions equivalent?

First definition:

class A
{
    std::string s;
};

Second definition:

class A
{
    std::string s;
public:
    A() : s() {  }
    ~A(){  }
    A(const A& AA) : s(AA.s) {  }
    A(A&& a) noexcept : s(std::move(a.s)) {  }
    A& operator=(const A& AA){
        s=AA.s;
        return *this;
    }
    A& operator=(A&& a) noexcept{
        s=(std::move(a.s));
        return *this;
    }
    const A* operator&() const{ return this; }
    A* operator&(){ return this; }
};

If they are not, could you show me a class definition that is equivalent to the first one, and explicitly defines all member functions of class A?

It depends on your definition of " equivalent ".

  • Assembly output of the code gen? Yes , for a good compiler and optimizer, they should be. :-)
  • Compiler's assumptions while generating ASTs and making class representations or Intermediate code? No , why?

... from C++14's standard draft n3797 (I believe it isn't so different from the main standard)..

To make things brief, Of the special member functions, taking a case of default constructor, we see from this section: (emphasis are mine)

12.1.5: .... Before the defaulted default constructor for a class is implicitly defined, all the non-user-provided default constructors for its base classes and its nonstatic data members shall have been implicitly defined. [ Note: An implicitly-declared default constructor has an exception-specification. An explicitly-defaulted definition might have an implicit exception specification, see 8.4. —end note ]

The above doesn't exactly apply to you code, nonetheless, further supporting evidence is somewhere in

12.6.3: A non-explicit copy/move constructor is a converting constructor. An implicitly-declared copy/move constructor is not an explicit constructor; it may be called for implicit type conversions.

Check for your self, there are many more supporting evidences ... So, in the standard's sense, once you explicitly define any special member function, its different from what the compiler would have created and its associated assumptions.

But at the end of the day, the same code may be generated by the code generator. :-) . Just that the assumptions of the compiler during compilation may be different.

TLDR;

There are a lot of other paragraphs in the standard(draft) where it makes distinctions between the effects of implicitly defined special member functions and its converse(its mostly silent on that). You can pick the standard up and search for all occurrences of the phrase "implicitly-defined"

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