简体   繁体   中英

Assign const ref to non-const object

In the following code we are returning a const object and collecting it in a non const object, and still it compiles without an error or a warning..

class foo
{
    int i;
public:
    const foo& call() const
    {
        return *this;
    }
};

int main()
{
    foo aa, bb;
    bb = aa.call();
}

You're actually taking a copy of a const object when you do bb = aa.call( ) which will call the implicit copy constructor on foo .

If you wanted to break the compilation then try:

foo aa;
foo& bb = aa.call( );

Note:

The implicit copy constructor is generally defined as:

foo( const foo& exist );

and in the default case just does a member-wise copy.

This code calls the implicitly defined copy assign operator foo& foo::operator=(const foo&) :

    int main()
    {
        foo aa, bb;
        bb = aa.call();//  equivalent to bb.operator=(aa.call());
    }

The argument to that assign operator is a const reference to foo, so can bind directly the reference returned by foo::call. There is no copy constructor called in any of this code.

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