hackingcpp / comments

Comments regarding hackingcpp.com
1 stars 0 forks source link

cpp/lang/references #5

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

C++ References Introduction | hacking C++

C++ references for beginners - properties, usage, guidelines, pitfalls: declaration, properties, const references, usage as function parameters, dangling, binding rules, etc.

https://hackingcpp.com/cpp/lang/references.html

jakr commented 3 years ago
  1. This chapter covers a lot of information, maybe the Binding Rules part could be separated / moved somewhere else?
  2. At the beginning, it does not say a lot about why one uses references, it starts directly with the first definition. In contrast, the pointer chapter has a nice introduction
  3. Since the chapters on references and pointers are not next to each other, it might be useful to link between them
  4. In one of the chapters, it would be nice to give some guidance on when to use pointers vs references (for example: prefer references; use pointers when null is allowed, use unique_ptr to express ownership, shared_ptr to control lifetime)
jakr commented 3 years ago

Forget about 4., the pointer chapter already contains it.

hackingcpp commented 3 years ago
  1. maybe, I have to think about it
  2. I agree, a short motivation at the beginning would be useful.
  3. definitely
mg979 commented 2 years ago

This compiles just fine with g++ (Windows)

#include <iostream>

int main()
{
    int  i  = 2;
    int  k  = 3;
    int& ri = i;    // reference to i
    ri = k;         //  COMPILER ERROR: reference can't be redirected
    std::cout << i; // 3
    // int& r2;        //  COMPILER ERROR: reference must be initialized
    // double& r3 = i; //  COMPILER ERROR: types must agree
}

I'm referring to the box at the top of this page, that says that a reference can't be redirected (but here I'm just assigning k value and not redirecting to k address right?).

hackingcpp commented 2 years ago

@mg979: you're absolutely right - I don't know what I was thinking when I wrote this. One more reason I plan to make all code boxes runnable in Compiler Explorer. As of now, only the standard library algorithm examples are all executable in the browser.

kooonnn commented 1 year ago

String literals are lvalues, we can get address of them like &"Hello World!".

JohannJo commented 8 months ago

In paragraph "Usage/ Const reference parameters" a closing parenthesis is missing on this line: if (y.empty() return x;