C++: Comments On: Constant references are not always your friends

Google recommended this.

First situation: Const Ref As Parameter

Conclusion of the first situation
Sometimes, constant references can perform implicit conversions.

That would be incorrect. Constant reference do not perform implicit conversion. In your example, “const char*” is an *argument to constructor*. Function argument is const ref. The reason why it works is, C++ allows temporaries to be referenced *in local function* by a const reference. So a temporary is created. It is referenced, since it’s not changed, you’re fine. Fun begins when you do following; now all bets are off:

void foo(const MyString &o)
{
    const_cast<MyString&>(o).saved_string = "fun";
    std::cout << o.saved_string << std::endl;
}

Explicit is when you don’t want a temporary to be created.
Template is by the cleanest but be careful, it can lead to code bloat.

Second Situation: Const Ref As Member

The first problem is name of member is still “saved_string”. Now it’s not saved; it’s just referred.
Heading “Using a constant reference stored in an object” is wrong, isn’t it? You are not using const ref member; you are using what it points to.
Heading “Trying to reassign a constant reference” – not sure it belongs here. It’s constant. Whether reference or not, reassiging is going to fail isn’t it?

If you try to work around that and de-constify the reference..

No, you are not de-constifying (that’s what I did above and mine is pretty crappy way to get around :)); you have changed data type.

Here are examples of types that should not be passed by const ref:
int (and short, long, float etc.)

This is mainly based on size. If you want to make somethingn const but avoid copy, BUT size of data type is same as const ref, make it just const for example sizeof int and int& are both 4 for long it’s 8. But general rule of thumb is right.

pointers

why not? It can be useful in completely contrived programming 🙂 :

    const char* p = "outer";
    try_const_char_ptr_vs_ptr_refs(p, p, p);
    std::cout << "p: " << p << std::endl; 


void try_const_char_ptr_vs_ptr_refs(const char* const_ptr, const char* const_ptr_ref, const char* const& const_ref_to_ptr) {
    const char * q = "inner";
    const_ptr = q;
    std::cout << "const_ptr: " << const_ptr << std::endl;
    
    const_ptr_ref = q;
    std::cout << "const_ptr_ref: " << const_ptr_ref << std::endl;
    
    // const_ref_to_ptr = q; // <=== NOT allowed,const ref to const ptr
    
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: