pointer not assigning value to variable

Hello,
the code bellow is self explanatory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>

class Foo 
{
public:
    Foo(std::string name) {name_ = name;};
    std::string name_;
};

int main()
{
    auto test = &Foo("hello");
    std::cout << test->name_ << std::endl;   // Resutl: nothing
    auto test2 =  new Foo("hello");
    std::cout << test2->name_ << std::endl;  // Result: "hello"
    auto test3 = Foo("hello");
    std::cout << test3.name_ << std::endl;   // Result: "hello"
}


Why in the first (test) nothing is printed?

thank you,
R
Last edited on
> Why in the first (test) case where test is a pointer, it doesn't retain the value

The lifetime of the temporary object is over at the end of the full statement on line #11.
test->name_ engenders undefined behaviour.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

class Foo 
{
public:
    Foo(std::string name) {name_ = name;}
    ~Foo() { std::cout << "Foo dies ..."; };
    
    std::string name_;
};

int main()
{
   auto test = &Foo("hello");
   std::cout << test->name_ << '\n';
   auto test2 = Foo("hi");
   std::cout << test2.name_ << '\n';
}



Standard g++ options ... can't compile.
test.cpp: In function 'int main()':
test.cpp:15:28: error: taking address of temporary [-fpermissive]
    auto test = &Foo("hello");



If you force it to compile with -fpermissive (not to be recommended):
Foo dies ...hello
hi
Foo dies ...

The Foo is dead before you try to reference it.
Last edited on
With VS, the error message is:

error C2102: '&' requires l-value


You can't take an address of a temp - rvalue - which is what Foo("hello") is.
Great, thank you all for the quick response.
All clear now.
Topic archived. No new replies allowed.