banner
cells

cells

为美好的世界献上 code

Q114

Q114#

#include <iostream>
#include <memory>
#include <vector>

class C {
public:
    void foo() {
        std::cout << "A";
    }
    void foo() const {
        std::cout << "B";
    }
};

struct S {
    std::vector<C> v;
    std::unique_ptr<C> u;
    C *const p;
    C const *p2;

    S() : v(1), u(new C()), p(u.get()), p2(u.get()) {

    }
};

int main() {
    S s;
    const S &r = s;
    s.v[0].foo();
    s.u->foo();
    s.p->foo();
    s.p2->foo();

    r.v[0].foo();
    r.u->foo();
    r.p->foo();
    r.p2->foo();
}

Answer#

click to see answer AAABBAAB

Explain#

The cv-qualifiers apply to the pointer and not to the object pointed to.

In the code above, the object s is non-const, and so its members all retain their default const-ness and all calls through them invoke the non-const version of C::foo(), but 'p2' is const, so it invoke the const version of C::foo().

r refers to its object as a const instance of S. That const-ness changes the behavior of its member v, an std::vector which is "const-correct" in the sense that its operator[] returns const C & and therefore invokes the const version of C::foo().

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.