Computer Backup
Computer Backup

Reputation: 187

c++ variable assignment makes code work

I have a class: Register.h

#pragma once
#include <string>

class Register {
public:
    Register(const std::string& name);
    void printName();

private:
    const std::string& m_name;
};

Register.cpp:

#include "Register.h"
#include <iostream>

Register::Register(const std::string& name) : m_name(name) {
}

void Register::printName() {
    std::cout << m_name << std::endl;
}

Main.cpp:

#include "Register.h"

int main() {
    const std::string name1 = "A";
    Register reg1(name1);
    reg1.printName();

    Register reg2("A");
    reg2.printName();

    getchar();
}

I would expect this to print "A" twice, however it prints "A" once and "" once. Please could you tall me the difference between the two options and how I could get the second to work, as I don't use name any where else in the function that creates reg?

Upvotes: 2

Views: 80

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Using

Register reg2("A");

implicitly creates a temporary std::string instance, and you initialize a reference member variable from it:

const std::string& m_name;

Register::Register(const std::string& name) : m_name(name) {
}

Lifetime of the temporary instance ends after the constructor call, and you have a dangling reference afterwards, accessing it is undefined behavior.

The initialization from a variable ensures that the reference is valid as long the variable is in scope and active.


To fix that problem simply make the m_name member variable a normal string instead of a const reference.

std::string m_name;

Upvotes: 8

Related Questions