Skip to content

Fix bug on initializing class member reference #355

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

ericzeng95
Copy link

#include <iostream>
class Animal {
public:
Animal(int age,std::string name):age_(age),name_(name) {
std::cout << "Animal(int age) is called" << std::endl;
}
private:
int &age_;
const std::string name_;
};
int main() {
Animal animal(10,"hh");
return 0;
}

The original code is wrong. Here class memebr reference variable age_ is binding to constructor parameter age, which is passed by value. When the constructor finishes, this variable goes out of scope, and the binded refernce age_ is dangling. All subsequent usage of age_ is undefined behaviour

@FlyDragonMan
Copy link

FlyDragonMan commented Jun 17, 2025 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants