0

I'm trying to unlearn using namespace std, considering https://www.youtube.com/watch?v=MZqjl9HEPZ8

So I tried


// using namespace std;

struct Data
{
    using std::shared_ptr;
    
    shared_ptr<char[]> m_name = nullptr;
    
//    std::shared_ptr<char[]> m_name = nullptr;
};

And from that I got

main.cpp:14:11: Using declaration in class refers into 'std::', which is not a class

It seems I cannot do using std::shared_ptr; inside class declaration?

Am I missing something or really need to type std::shared_ptr there?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
KcFnMi
  • 5,516
  • 10
  • 62
  • 136

2 Answers2

1

From the C++ 17 Standard (10.3.3 The using declaration)

3 In a using-declaration used as a member-declaration, each using-declarator’s nested-name-specifier shall name a base class of the class being defined. If a using-declarator names a constructor, its nested-name-specifier shall name a direct base class of the class being defined.

std::shared_ptr is not a member of a base class of the class Data in your code example.

So the compiler issues an error.

std:;shared_ptr is a class declared in the namespace std. It is not even a member of some class.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Certain forms of using don't work in class bodies. This includes using namespace and using X where X isn't inherited from the base class.

using std::shared_ptr; works if you move it to the global scope.

using X = Y; does work at class scope. In your case, it would be template <typename T> using shared_ptr = std::shared_ptr<T>;. But note that in rare cases it's slightly different from spelling it as std::shared_ptr (e.g. when passing it to template template parameters).


[do I] really need to type std::shared_ptr there?

You should type std::shared_ptr. Omitting std:: often causes confusion. "Is it something from std:: or something custom?"

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207