-2

I am learning about smart pointers and when trying to compile the following "stupid" code I get an error.

#include <memory>
#include <iostream>

class Test
{
    std::string myString="dumm";
};

int main()
{

    std::unique_ptr<Test> test(new Test());
    std::cout<<test->myString<<std::endl;

    return 0;
}

I just wanted to see, whether this works but I get :"Applying -> to std::unique_ptr instead of a pointer", which seems weird.

I am using c++ 11

Eit: The error is now fixed and I cancompile the above code. However, CLion still gives me "Cant apply -> to std::uniq_ptr"-stuff, which seems to be an error with the IDE

CheckersGuy
  • 117
  • 10

1 Answers1

4

In a class the default visibility is private which makes the myString field invisible to the test object. Make it public:

#include <iostream>
#include <memory>
#include <string>

class Test {
public:
    std::string myString = "dumm";
};

int main() {
    std::unique_ptr<Test> test(new Test());
    std::cout << test->myString;
}

Prefer std::make_unique to direct use of new if compiling for C++14 and later:

std::unique_ptr<Test> test = std::make_unique<Test>();

This function is not available in the C++11 standard which is what you are using.

Ron
  • 14,674
  • 4
  • 34
  • 47
  • Thanks. Coming from java and member variables are protected by default (If I am not mistaken). Stupid error by me but thanks anyways – CheckersGuy Jan 07 '18 at 23:36
  • `Prefer std::make_unique to direct use of new:` You should probably mention that `std::make_unique` is not in the C++11 standard that CheckersGuy uses. That said, it's trivial to implement your own `make_unique`. – eerorika Jan 07 '18 at 23:39
  • @CheckersGuy, Java's default access level for members is package-private. – chris Jan 07 '18 at 23:41
  • @user Not entirely trivial https://stackoverflow.com/questions/17902405/how-to-implement-make-unique-function-in-c11 –  Jan 07 '18 at 23:42